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:com.confighub.core.utils.Utils.java

License:Open Source License

private static boolean isJsonValid(final Reader reader) throws IOException {
    return isJsonValid(new JsonReader(reader));
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

License:Open Source License

private JsonElement extractResponse(HttpResponse res, HttpRequestBase req, int expectCode)
        throws RestApiException, IOException {

    JsonElement ret;/*from   ww  w .j  ava2  s .co  m*/
    HttpEntity entity;
    entity = res.getEntity();
    if (entity == null) {
        ret = new JsonObject();

    } else {
        Header contentType = entity.getContentType();
        if (contentType == null || contentType.getValue().contains("json") == false) {
            ret = new JsonObject();
            ret.getAsJsonObject().addProperty("__raw_response", IOUtils.toString(entity.getContent()));
        } else {
            JsonReader reader = new JsonReader(new InputStreamReader(entity.getContent()));
            ret = gs.fromJson(reader, JsonObject.class);
        }
    }
    if (res.getStatusLine().getStatusCode() != expectCode) {
        throw new RestApiException(ret, res.getStatusLine(), req);
    }

    return ret;
}

From source file:com.dabay6.libraries.androidshared.ui.dialogs.changelog.util.ChangeLogDialogUtils.java

License:Open Source License

/**
 * Builds the html using the change log json asset file.
 *
 * @param context   {@link Context} used to retrieve resources.
 * @param assetName Name of the asset file containing the change log json.
 * @param style     The css style to be applied to the html.
 *
 * @return A {@link String} containing html.
 *//* w ww  . java2 s  . c  o  m*/
private static String getHtmlChangeLog(final Context context, final String assetName, final String style)
        throws IOException {
    final JsonReader reader;
    final Gson gson = new Gson();
    final List<Release> releases = ListUtils.newList();
    String html = null;

    try {
        reader = new JsonReader(new InputStreamReader(AssetUtils.open(context, assetName), "UTF-8"));
        reader.beginArray();

        while (reader.hasNext()) {
            final Release release = gson.fromJson(reader, Release.class);

            releases.add(release);
        }

        reader.endArray();
        reader.close();

        if (releases.size() > 0) {
            html = String.format("<html><head>%s</head><body>", style);
            html += parseReleases(context, releases);
            html += "</body></html>";
        }
    } catch (final Exception ex) {
        html = null;

        Logger.error(TAG, ex.getMessage(), ex);
    }

    return html;
}

From source file:com.division.jsonrpc.JsonClient.java

License:Apache License

public void sendRequest(final JsonRequest request, final Type returnType, final RPCCallback callback) {
    Thread t = new Thread() {
        public void run() {
            RPCTransport response;/*w  ww . j  a v a2s  .  c  o  m*/
            String jRequest = gson.toJson(request);
            HttpURLConnection urlConnection = null;
            try {
                URL server = new URL(rpcServer);
                urlConnection = (HttpURLConnection) server.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("content-type", "application/json");
                urlConnection.setDoOutput(true);
                OutputStream oStream = urlConnection.getOutputStream();
                System.out.println(jRequest);
                oStream.write(jRequest.getBytes());
                oStream.flush();
                oStream.close();

                InputStream rStream = urlConnection.getInputStream();
                String responseString = "";
                int bytes;
                byte[] bytesRec = new byte[51200];
                while ((bytes = rStream.read(bytesRec, 0, bytesRec.length)) != -1) {
                    responseString += new String(bytesRec, 0, bytes);
                }
                rStream.close();
                responseString = responseString.trim();
                if (callback != null) {
                    JsonReader jReader = new JsonReader(new StringReader(responseString));
                    jReader.setLenient(true);
                    response = gson.fromJson(jReader, returnType);
                    callback.onResponseReceived(response);
                }
                urlConnection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("JSONRPC: EXCEPTION");
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        }
    };
    t.setDaemon(true);
    t.start();
}

From source file:com.driver733.vkuploader.wallpost.attachment.support.QueryResultsBasic.java

License:Open Source License

@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public List<JsonElement> results() throws IOException {
    final List<AbstractQueryBuilder> constructed = this.queries.queries();
    final List<JsonElement> results = new ArrayList<>(constructed.size());
    for (final AbstractQueryBuilder query : constructed) {
        if (query.isCached()) {
            final String response;
            try {
                response = query.executeAsString();
            } catch (final ClientException ex) {
                throw new IOException("Failed to execute the query", ex);
            }/*from  w  ww . j av  a  2s.  c  o m*/
            results.add(new JsonParser().parse(new JsonReader(new StringReader(response))));
        }
    }
    return new StickyList<>(results);
}

From source file:com.epam.wilma.core.processor.entity.PrettyPrintProcessor.java

License:Open Source License

private String tryToParseJson(final WilmaHttpEntity entity, final String body) {
    String result = body;/*  www .ja  va  2s .  c om*/
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
        JsonParser parser = new JsonParser();
        JsonReader reader = new JsonReader(new StringReader(body));
        reader.setLenient(true);
        JsonElement element = parser.parse(reader);
        result = gson.toJson(element);
    } catch (Exception e) {
        logError(entity, e);
    }
    return result;
}

From source file:com.esotericsoftware.spine.SkeletonJson.java

License:Open Source License

public SkeletonData readSkeletonData(String folder, String file) {
    float scale = this.scale;

    SkeletonData skeletonData = new SkeletonData();
    //skeletonData.name = file.nameWithoutExtension();
    skeletonData.name = file;/*from www. ja  va  2  s.com*/

    //JsonValue root = new JsonReader().parse(file);
    try (InputStreamReader isReader = new InputStreamReader(
            ResourceLoader.getResourceAsStream(folder + "/" + file + ".json"))) {
        JsonReader reader = new JsonReader(isReader);
        JsonParser parser = new JsonParser();

        JsonObject root = (JsonObject) parser.parse(reader);

        // Skeleton.
        JsonObject skeletonMap = root.get("skeleton").getAsJsonObject();
        if (skeletonMap != null) {
            skeletonData.hash = skeletonMap.has("hash") ? skeletonMap.get("hash").getAsString() : null;
            skeletonData.version = skeletonMap.has("spine") ? skeletonMap.get("spine").getAsString() : null;
            skeletonData.width = skeletonMap.has("width") ? skeletonMap.get("width").getAsFloat() : 0;
            skeletonData.height = skeletonMap.has("height") ? skeletonMap.get("height").getAsFloat() : 0;
            skeletonData.imagesPath = skeletonMap.has("images") ? skeletonMap.get("images").getAsString()
                    : null;
        }

        // Bones.
        //for (JsonValue boneMap = root.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
        for (JsonElement boneMap : root.get("bones").getAsJsonArray()) {
            JsonObject currentBone = boneMap.getAsJsonObject();
            BoneData parent = null;
            String parentName = currentBone.has("parent") ? currentBone.get("parent").getAsString() : null;
            if (parentName != null) {
                parent = skeletonData.findBone(parentName);
                if (parent == null)
                    throw new SerializationException("Parent bone not found: " + parentName);
            }
            BoneData boneData = new BoneData(currentBone.get("name").getAsString(), parent);
            boneData.length = (currentBone.has("length") ? currentBone.get("length").getAsFloat() : 0) * scale;//boneMap.getFloat("length", 0) * scale;
            boneData.x = (currentBone.has("x") ? currentBone.get("x").getAsFloat() : 0) * scale;//boneMap.getFloat("x", 0) * scale;
            boneData.y = (currentBone.has("y") ? currentBone.get("y").getAsFloat() : 0) * scale;//boneMap.getFloat("y", 0) * scale;
            boneData.rotation = currentBone.has("rotation") ? currentBone.get("rotation").getAsFloat() : 0;//boneMap.getFloat("rotation", 0);
            boneData.scaleX = currentBone.has("scaleX") ? currentBone.get("scaleX").getAsFloat() : 1;//boneMap.getFloat("scaleX", 1);
            boneData.scaleY = currentBone.has("scaleY") ? currentBone.get("scaleY").getAsFloat() : 1;//boneMap.getFloat("scaleY", 1);
            boneData.flipX = currentBone.has("flipX") ? currentBone.get("flipX").getAsBoolean() : false;//boneMap.getBoolean("flipX", false);
            boneData.flipY = currentBone.has("flipY") ? currentBone.get("flipY").getAsBoolean() : false;//boneMap.getBoolean("flipY", false);
            boneData.inheritScale = currentBone.has("inheritScale")
                    ? currentBone.get("inheritScale").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritScale", true);
            boneData.inheritRotation = currentBone.has("inheritRotation")
                    ? currentBone.get("inheritRotation").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritRotation", true);

            String color = currentBone.has("color") ? currentBone.get("color").getAsString() : null;//boneMap.getString("color", null);
            if (color != null)
                boneData.getColor().set(Color.valueOf(color));

            skeletonData.bones.add(boneData);
        }

        // IK constraints.
        // TODO May return a JsonObject not Array
        //for (JsonValue ikMap = root.getChild("ik"); ikMap != null; ikMap = ikMap.next) {
        if (root.has("ik")) {
            for (JsonElement ikMap : root.get("ik").getAsJsonArray()) {
                JsonObject currentIk = ikMap.getAsJsonObject();
                IkConstraintData ikConstraintData = new IkConstraintData(currentIk.get("name").getAsString());

                //for (JsonValue boneMap = ikMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
                for (JsonElement boneMap : currentIk.get("bones").getAsJsonArray()) {
                    String boneName = boneMap.getAsString();
                    BoneData bone = skeletonData.findBone(boneName);
                    if (bone == null)
                        throw new SerializationException("IK bone not found: " + boneName);
                    ikConstraintData.bones.add(bone);
                }

                String targetName = currentIk.get("target").getAsString();
                ikConstraintData.target = skeletonData.findBone(targetName);
                if (ikConstraintData.target == null)
                    throw new SerializationException("Target bone not found: " + targetName);

                ikConstraintData.bendDirection = (currentIk.has("bendPositive")
                        ? currentIk.get("bendPositive").getAsBoolean()
                        : true) ? 1 : -1;//ikMap.getBoolean("bendPositive", true) ? 1 : -1;
                ikConstraintData.mix = currentIk.has("mix") ? currentIk.get("mix").getAsFloat() : 1;//ikMap.getFloat("mix", 1);

                skeletonData.ikConstraints.add(ikConstraintData);
            }
        }

        // Slots.
        //for (JsonValue slotMap = root.getChild("slots"); slotMap != null; slotMap = slotMap.next) {
        for (JsonElement slotMap : root.get("slots").getAsJsonArray()) {
            JsonObject currentSlot = slotMap.getAsJsonObject();
            String slotName = currentSlot.get("name").getAsString();
            String boneName = currentSlot.get("bone").getAsString();
            BoneData boneData = skeletonData.findBone(boneName);
            if (boneData == null)
                throw new SerializationException("Slot bone not found: " + boneName);
            SlotData slotData = new SlotData(slotName, boneData);

            String color = currentSlot.has("color") ? currentSlot.get("color").getAsString() : null;//slotMap.getString("color", null);
            if (color != null)
                slotData.getColor().set(Color.valueOf(color));

            slotData.attachmentName = currentSlot.has("attachment")
                    ? currentSlot.get("attachment").getAsString()
                    : null;//slotMap.getString("attachment", null);

            slotData.additiveBlending = currentSlot.has("additive") ? currentSlot.get("additive").getAsBoolean()
                    : false;//slotMap.getBoolean("additive", false);

            skeletonData.slots.add(slotData);
        }

        // Skins.
        //for (JsonValue skinMap = root.getChild("skins"); skinMap != null; skinMap = skinMap.next) {
        for (Entry<String, JsonElement> skinMap : root.get("skins").getAsJsonObject().entrySet()) {
            Skin skin = new Skin(skinMap.getKey());
            //for (JsonValue slotEntry = skinMap.child; slotEntry != null; slotEntry = slotEntry.next) {
            for (Entry<String, JsonElement> slotEntry : skinMap.getValue().getAsJsonObject().entrySet()) {
                int slotIndex = skeletonData.findSlotIndex(slotEntry.getKey());
                if (slotIndex == -1)
                    throw new SerializationException("Slot not found: " + slotEntry.getKey());
                //for (JsonValue entry = slotEntry.child; entry != null; entry = entry.next) {
                for (Entry<String, JsonElement> entry : slotEntry.getValue().getAsJsonObject().entrySet()) {
                    Attachment attachment = readAttachment(skin, entry.getKey(),
                            entry.getValue().getAsJsonObject());
                    if (attachment != null) {
                        skin.addAttachment(slotIndex, entry.getKey(), attachment);
                    }
                }
            }
            skeletonData.skins.add(skin);
            if (skin.name.equals("default"))
                skeletonData.defaultSkin = skin;
        }

        // Events.
        //for (JsonValue eventMap = root.getChild("events"); eventMap != null; eventMap = eventMap.next) {
        if (root.has("events")) {
            for (Entry<String, JsonElement> eventMap : root.get("events").getAsJsonObject().entrySet()) {
                JsonObject currentEvent = eventMap.getValue().getAsJsonObject();
                EventData eventData = new EventData(eventMap.getKey());
                eventData.intValue = currentEvent.has("int") ? currentEvent.get("int").getAsInt() : 0;//eventMap.getInt("int", 0);
                eventData.floatValue = currentEvent.has("float") ? currentEvent.get("float").getAsFloat() : 0f;//eventMap.getFloat("float", 0f);
                eventData.stringValue = currentEvent.has("string") ? currentEvent.get("string").getAsString()
                        : null;//eventMap.getString("string", null);
                skeletonData.events.add(eventData);
            }
        }

        // Animations.
        //for (JsonValue animationMap = root.getChild("animations"); animationMap != null; animationMap = animationMap.next)
        for (Entry<String, JsonElement> animationMap : root.get("animations").getAsJsonObject().entrySet()) {
            readAnimation(animationMap.getKey(), animationMap.getValue().getAsJsonObject(), skeletonData);
        }

    } catch (JsonIOException | IOException e) {
        e.printStackTrace();
    }

    /*skeletonData.bones.shrink();
    skeletonData.slots.shrink();
    skeletonData.skins.shrink();
    skeletonData.animations.shrink();*/
    return skeletonData;
}

From source file:com.esri.gpt.framework.dcat.DcatParser.java

License:Apache License

/**
 * Creates instance of the parser./* ww w . jav  a2  s.  c  om*/
 *
 * @param input input stream to parse
 */
public DcatParser(InputStream input) throws UnsupportedEncodingException {
    this.jsonReader = new JsonReader(new InputStreamReader(input, "UTF-8"));
}

From source file:com.esri.gpt.framework.dcat.DcatParser.java

License:Apache License

/**
 * Creates instance of the parser.
 *
 * @param reader data reader
 */
public DcatParser(Reader reader) {
    this.jsonReader = new JsonReader(reader);
}

From source file:com.example.app.tweetui.ListTimelineFragment.java

License:Apache License

private TimelineFilter getBasicTimelineFilter() {
    final InputStream inputStream = getContext().getResources().openRawResource(R.raw.filter_values);
    final JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
    final FilterValues filterValues = new Gson().fromJson(reader, FilterValues.class);
    return new BasicTimelineFilter(filterValues);
}