Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader JsonReader.

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:co.cask.cdap.security.store.KeyStoreEntry.java

License:Apache License

/**
 * Deserialize a new metadata object from a byte array.
 *
 * @param buf the serialized metadata//from w  w  w .j a v  a2s  .c  o  m
 */
private static SecureStoreMetadata deserializeMetadata(byte[] buf) throws IOException {
    try (JsonReader reader = new JsonReader(
            new InputStreamReader(new ByteArrayInputStream(buf), Charset.forName("UTF-8")))) {
        return KeyStoreEntry.GSON.fromJson(reader, SecureStoreMetadata.class);
    }
}

From source file:co.cask.cdap.test.internal.MockResponder.java

License:Apache License

public <T> T decodeResponseContent(TypeToken<T> type) {
    JsonReader jsonReader = new JsonReader(
            new InputStreamReader(new ChannelBufferInputStream(content), Charsets.UTF_8));
    return GSON.fromJson(jsonReader, type.getType());
}

From source file:co.mitro.core.servlets.ServerRejectsServlet.java

License:Open Source License

/**
 * Sets the server hints to hintsString, after validation. Throws exceptions if the JSON data
 * is incorrect, although the validation isn't currently extremely careful.
 *///from   w  w w  .j  a v a 2s.c  o m
public static void setServerHintsJson(String hintsString) {
    try {
        // Parse and validate the hints
        // TODO: Unit test this more carefully

        // can't use gson.fromJson() because it always uses lenient parsing; copied from there
        // See https://code.google.com/p/google-gson/issues/detail?id=372
        JsonReader jsonReader = new JsonReader(new StringReader(hintsString));
        TypeAdapter<?> typeAdapter = gson.getAdapter(TypeToken.get(listType));
        @SuppressWarnings("unchecked")
        List<HintEntry> hints = (List<HintEntry>) typeAdapter.read(jsonReader);

        for (HintEntry hint : hints) {
            @SuppressWarnings("unused")
            Pattern regexp = Pattern.compile(hint.regex);

            if (hint.additional_submit_button_ids != null) {
                // optional: just don't include it instead of including an empty list
                assert hint.additional_submit_button_ids.size() > 0;
                for (String submitIds : hint.additional_submit_button_ids) {
                    assert !Strings.isNullOrEmpty(submitIds);
                }
            }

            if (hint.allow_empty_username != null) {
                assert hint.allow_empty_username : "omit allow_empty_username if false";
            }

            if (hint.empty_password_username_selector != null) {
                // TODO: Validate that this is a valid CSS selector?
                assert !hint.empty_password_username_selector
                        .isEmpty() : "omit empty_password_username_selector if there is no selector";
                assert hint.allow_empty_username != null && hint.allow_empty_username
                        .booleanValue() : "allow_empty_username must be true if empty_password_username_selector is present";
            }

            validateRules(hint.reject.login_submit);
            validateRules(hint.reject.submit);
            validateRules(hint.reject.password);
            validateRules(hint.reject.username);
            validateRules(hint.reject.form);
        }
        logger.info("setting {} server hints", hints.size());

        serverHintsJson = hintsString;
    } catch (IOException | IllegalStateException e) {
        // Rethrow the same way as gson.fromJson()
        throw new JsonSyntaxException(e);
    }
}

From source file:co.moonmonkeylabs.flowmortarexampleapp.common.flow.GsonParceler.java

License:Apache License

private Object decode(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));

    try {//from  ww w .j  av  a2 s . c o m
        reader.beginObject();

        Class<?> type = Class.forName(reader.nextName());
        return gson.fromJson(reader, type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        reader.close();
    }
}

From source file:co.runrightfast.zest.fragments.mixins.json.GsonValueSerialization.java

License:Apache License

@Override
public <T> T deserialize(final Class<?> type, final InputStream in) throws ValueSerializationException {
    try (final JsonReader reader = new JsonReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
        return gson.fromJson(reader, type);
    } catch (final IOException e) {
        throw new ValueSerializationException(e);
    }//from w w w  .j a  va2s .c  o  m
}

From source file:co.runrightfast.zest.fragments.mixins.json.GsonValueSerialization.java

License:Apache License

@Override
public <T> T deserialize(final ValueType valueType, InputStream in) throws ValueSerializationException {
    try (final JsonReader reader = new JsonReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
        return gson.fromJson(reader, valueType.mainType());
    } catch (final IOException e) {
        throw new ValueSerializationException(e);
    }/*www  .ja v a2 s. co  m*/
}

From source file:cognition.common.helper.JsonHelper.java

License:Apache License

public List<T> loadFromReader(Reader reader) {
    Gson gson = new Gson();

    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(reader);
    JsonReader jsonReader = new JsonReader(bufferedReader);
    jsonReader.setLenient(true);/*from w  ww .  j  a va  2  s  . co m*/
    if (!clazz.isArray()) {
        Object data = gson.fromJson(jsonReader, clazz);
        T object = (T) data;
        return Arrays.asList(object);
    }

    Object[] data = gson.fromJson(jsonReader, clazz);
    return Arrays.asList((T[]) data);
}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

@Override
public Bundleizer createBundleizer(final InputStream inputArg, final BundleFactory factoryArg) {
    return new Bundleizer() {
        private final BundleFactory factory = factoryArg;
        private final JsonParser parser = new JsonParser();
        private final JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(inputArg)));

        {/*from   w  w  w.j  av a 2s .c o m*/
            try {
                reader.beginArray();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public Bundle next() throws IOException {
            if (reader.hasNext()) {
                JsonObject nextElement = parser.parse(reader).getAsJsonObject();
                Bundle next = factory.createBundle();
                BundleFormat format = next.getFormat();
                for (Map.Entry<String, JsonElement> entry : nextElement.entrySet()) {
                    next.setValue(format.getField(entry.getKey()), fromGson(entry.getValue()));
                }
                return next;
            } else {
                return null;
            }
        }
    };
}

From source file:com.aliakseipilko.flightdutytracker.utils.AirportCodeConverter.java

License:Open Source License

private void generateAirports() {
    JsonReader jsonReader = new JsonReader(
            new InputStreamReader(ctx.getResources().openRawResource(R.raw.airports)));
    try {/*from  ww  w. j ava  2  s  . com*/
        jsonReader.beginArray();
        while (jsonReader.hasNext()) {
            Airport airport = gson.fromJson(jsonReader, Airport.class);
            if (airport.getIATA() == null) {
                airport.setIATA("");
            }
            if (airport.getICAO() == null) {
                airport.setICAO("");
            }
            airports.add(airport);
        }
        jsonReader.endArray();
        jsonReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.aliyun.openservices.odps.console.common.JobDetailInfo.java

License:Apache License

private List<FuxiJob> loadJobsFromStream(InputStream in) throws ODPSConsoleException {
    boolean debug = true;
    ArrayList<FuxiJob> jobs = new ArrayList<FuxiJob>();
    if (debug) {//from   www  . java  2  s.c  o  m
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("mapReduce")) {
                    reader.beginObject();
                    while (reader.hasNext()) {
                        String nameInMapReduce = reader.nextName();
                        if (nameInMapReduce.equals("jobs")) {
                            reader.beginArray();
                            while (reader.hasNext()) {
                                jobs.add(getFuxiJobFromJson(reader));
                            }
                            reader.endArray();
                        } else if (nameInMapReduce.equals("jsonSummary")) {
                            getInfoFromJsonSummary(jobs, reader.nextString());
                        } else {
                            reader.skipValue();
                        }
                    }
                    reader.endObject();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ODPSConsoleException("Bad json format");
        }
    }

    return jobs;
}