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

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

Introduction

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

Prototype

public void beginObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Usage

From source file:com.patloew.countries.util.RealmStringMapEntryListTypeAdapter.java

License:Apache License

@Override
public RealmList<RealmStringMapEntry> read(JsonReader in) throws IOException {
    RealmList<RealmStringMapEntry> mapEntries = new RealmList<>();

    in.beginObject();

    while (in.hasNext()) {
        RealmStringMapEntry realmStringMapEntry = new RealmStringMapEntry();
        realmStringMapEntry.key = in.nextName();

        if (in.peek() == JsonToken.NULL) {
            in.nextNull();/*from   w w  w . ja va2s. c  o  m*/
            realmStringMapEntry.value = null;
        } else {
            realmStringMapEntry.value = in.nextString();
        }

        mapEntries.add(realmStringMapEntry);
    }

    in.endObject();

    return mapEntries;
}

From source file:com.pocketbeer.presentation.flow.GsonParceler.java

License:Apache License

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

    try {//w  ww .  ja v  a  2s.  c  o m
        reader.beginObject();

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

From source file:com.ptapp.sync.PTAppDataHandler.java

License:Open Source License

/**
 * Processes a conference data body and calls the appropriate data type handlers
 * to process each of the objects represented therein.
 *
 * @param dataBody The body of data to process
 * @throws java.io.IOException If there is an error parsing the data.
 *//*www. ja  va2s  .com*/
private void processDataBody(String dataBody) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(dataBody));
    JsonParser parser = new JsonParser();
    try {
        reader.setLenient(true); // To err is human

        // the whole file is a single JSON object
        reader.beginObject();

        while (reader.hasNext()) {
            // the key is "educators", "courses", "students", "events" etc.
            String key = reader.nextName();
            if (mHandlerForKey.containsKey(key)) {
                // pass the value to the corresponding handler
                mHandlerForKey.get(key).process(parser.parse(reader));
            } else {
                LOGW(TAG, "Skipping unknown key in ptapp data json: " + key);
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.qdeve.oilprice.configuration.GsonMoneyTypeAdapter.java

License:Apache License

@Override
public Money read(JsonReader in) throws IOException {
    String currency = null;//from  w  w w .ja  va  2 s . c  om
    Double price = null;
    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
        case CURRENTY_TAG:
            currency = in.nextString();
            break;
        case PRICE_TAG:
            price = in.nextDouble();
            break;
        }
    }
    in.endObject();
    return MonetaryUtils.newMoneyFrom(price, currency);
}

From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java

License:Open Source License

/**
 * can parse json like {"items":[{"id":6782}]}
 * @param in/*  w w  w .j a va2s.  c  om*/
 * @param iJoBj
 * @return count all, count new items
 * @throws IOException
 */
public static int[] readJsonStreamV2(InputStream in, IHandleJsonObject iJoBj) throws IOException {
    List<String> allowedArrays = Arrays.asList("feeds", "folders", "items");

    int count = 0;
    int newItemsCount = 0;
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    reader.beginObject();

    String currentName;
    while (reader.hasNext() && (currentName = reader.nextName()) != null) {
        if (allowedArrays.contains(currentName))
            break;
        else
            reader.skipValue();
    }

    reader.beginArray();
    while (reader.hasNext()) {
        JSONObject e = getJSONObjectFromReader(reader);

        if (iJoBj.performAction(e))
            newItemsCount++;

        count++;
    }

    if (iJoBj instanceof InsertItemIntoDatabase)
        ((InsertItemIntoDatabase) iJoBj).performDatabaseBatchInsert(); //Save pending buffer

    //reader.endArray();
    //reader.endObject();
    reader.close();

    return new int[] { count, newItemsCount };
}

From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java

License:Open Source License

/**
 * can parse json like {"items":[{"id":6782}]}
 * @param in//from   w  w  w .  j a v a 2  s.  c o  m
 * @param iJoBj
 * @return new int[] { count, newItemsCount }
 * @throws IOException
 */
public static int[] readJsonStreamV1(InputStream in, IHandleJsonObject iJoBj) throws IOException {
    int count = 0;
    int newItemsCount = 0;
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    reader.beginObject();//{
    reader.nextName();//"ocs"
    reader.beginObject();//{
    reader.nextName();//meta

    getJSONObjectFromReader(reader);//skip status etc.

    reader.nextName();//data
    reader.beginObject();//{
    reader.nextName();//folders etc..

    reader.beginArray();
    while (reader.hasNext()) {
        //reader.beginObject();

        JSONObject e = getJSONObjectFromReader(reader);

        if (iJoBj.performAction(e))
            newItemsCount++;

        //reader.endObject();
        count++;
    }

    if (iJoBj instanceof InsertItemIntoDatabase)
        ((InsertItemIntoDatabase) iJoBj).performDatabaseBatchInsert(); //Save pending buffer

    //reader.endArray();
    //reader.endObject();
    reader.close();

    return new int[] { count, newItemsCount };
}

From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java

License:Open Source License

private static JSONObject getJSONObjectFromReader(JsonReader jsonReader) {
    JSONObject jObj = new JSONObject();
    JsonToken tokenInstance;/*from w w w .  j  a  v a2  s.com*/
    try {
        tokenInstance = jsonReader.peek();
        if (tokenInstance == JsonToken.BEGIN_OBJECT)
            jsonReader.beginObject();
        else if (tokenInstance == JsonToken.BEGIN_ARRAY)
            jsonReader.beginArray();

        while (jsonReader.hasNext()) {
            JsonToken token;
            String name;
            try {
                name = jsonReader.nextName();
                token = jsonReader.peek();

                //Log.d(TAG, token.toString());

                switch (token) {
                case NUMBER:
                    jObj.put(name, jsonReader.nextLong());
                    break;
                case NULL:
                    jsonReader.skipValue();
                    break;
                case BOOLEAN:
                    jObj.put(name, jsonReader.nextBoolean());
                    break;
                case BEGIN_OBJECT:
                    //jsonReader.beginObject();
                    jObj.put(name, getJSONObjectFromReader(jsonReader));
                    //jsonReader.endObject();
                    break;
                case BEGIN_ARRAY:
                    jsonReader.skipValue();
                    break;
                default:
                    jObj.put(name, jsonReader.nextString());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                jsonReader.skipValue();
            }
        }

        if (tokenInstance == JsonToken.BEGIN_OBJECT)
            jsonReader.endObject();
        else if (tokenInstance == JsonToken.BEGIN_ARRAY)
            jsonReader.endArray();

        return jObj;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.razza.apps.iosched.sync.ConferenceDataHandler.java

License:Open Source License

/**
 * Processes a conference data body and calls the appropriate data type handlers
 * to process each of the objects represented therein.
 *
 * @param dataBody The body of data to process
 * @throws IOException If there is an error parsing the data.
 *//* w w  w .  j a  v  a  2  s .c  o  m*/
private void processDataBody(String dataBody) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(dataBody));
    JsonParser parser = new JsonParser();
    try {
        reader.setLenient(true); // To err is human

        // the whole file is a single JSON object
        reader.beginObject();

        while (reader.hasNext()) {
            // the key is "rooms", "speakers", "tracks", etc.
            String key = reader.nextName();
            if (mHandlerForKey.containsKey(key)) {
                // pass the value to the corresponding handler
                mHandlerForKey.get(key).process(parser.parse(reader));
            } else {
                LogUtils.LOGW(TAG, "Skipping unknown key in conference data json: " + key);
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.redhat.thermostat.gateway.common.mongodb.response.LongTypeAdapter.java

License:Open Source License

@Override
public Long read(JsonReader in) throws IOException {
    in.beginObject();
    String name = in.nextName();// w ww  . j a  va 2 s .c o m
    if (!name.equals(NUMBER_LONG_IDENTIFIER)) {
        throw new JsonSyntaxException("Unexpected name: " + name);
    }
    long returnValue = in.nextLong();
    in.endObject();
    return returnValue;
}

From source file:com.replaymod.replaystudio.pathing.serialize.LegacyKeyframeSetAdapter.java

License:MIT License

@SuppressWarnings("unchecked")
@Override// ww  w  .  j a v  a 2  s  .  com
public KeyframeSet[] read(JsonReader in) throws IOException {
    List<KeyframeSet> sets = new ArrayList<>();

    in.beginArray();
    while (in.hasNext()) { //iterate over all array entries

        KeyframeSet set = new KeyframeSet();
        List<Keyframe> positionKeyframes = new ArrayList<>();
        List<Keyframe> timeKeyframes = new ArrayList<>();

        in.beginObject();
        while (in.hasNext()) { //iterate over all object entries
            String jsonTag = in.nextName();

            if ("name".equals(jsonTag)) {
                set.name = in.nextString();

                //TODO: Adapt to new Spectator Keyframe system
            } else if ("positionKeyframes".equals(jsonTag)) {
                in.beginArray();
                while (in.hasNext()) {
                    Keyframe<AdvancedPosition> newKeyframe = new Keyframe<>();
                    Integer spectatedEntityID = null;
                    in.beginObject();
                    while (in.hasNext()) {
                        String jsonKeyframeTag = in.nextName();
                        if ("value".equals(jsonKeyframeTag) || "position".equals(jsonKeyframeTag)) {
                            SpectatorData spectatorData = new Gson().fromJson(in, SpectatorData.class);
                            if (spectatorData.spectatedEntityID != null) {
                                newKeyframe.value = spectatorData;
                            } else {
                                newKeyframe.value = new AdvancedPosition();
                                newKeyframe.value.x = spectatorData.x;
                                newKeyframe.value.y = spectatorData.y;
                                newKeyframe.value.z = spectatorData.z;
                                newKeyframe.value.yaw = spectatorData.yaw;
                                newKeyframe.value.pitch = spectatorData.pitch;
                                newKeyframe.value.roll = spectatorData.roll;
                            }
                        } else if ("realTimestamp".equals(jsonKeyframeTag)) {
                            newKeyframe.realTimestamp = in.nextInt();
                        } else if ("spectatedEntityID".equals(jsonKeyframeTag)) {
                            spectatedEntityID = in.nextInt();
                        }
                    }

                    if (spectatedEntityID != null) {
                        AdvancedPosition pos = newKeyframe.value;
                        SpectatorData spectatorData = new SpectatorData();
                        spectatorData.spectatedEntityID = spectatedEntityID;
                        newKeyframe.value = spectatorData;
                        newKeyframe.value.x = pos.x;
                        newKeyframe.value.y = pos.y;
                        newKeyframe.value.z = pos.z;
                        newKeyframe.value.yaw = pos.yaw;
                        newKeyframe.value.pitch = pos.pitch;
                        newKeyframe.value.roll = pos.roll;
                    }

                    in.endObject();

                    positionKeyframes.add(newKeyframe);
                }
                in.endArray();

            } else if ("timeKeyframes".equals(jsonTag)) {
                in.beginArray();
                while (in.hasNext()) {
                    Keyframe<TimestampValue> newKeyframe = new Keyframe<>();

                    in.beginObject();
                    while (in.hasNext()) {
                        String jsonKeyframeTag = in.nextName();
                        if ("timestamp".equals(jsonKeyframeTag)) {
                            TimestampValue timestampValue = new TimestampValue();
                            timestampValue.value = in.nextInt();
                            newKeyframe.value = timestampValue;
                        } else if ("value".equals(jsonKeyframeTag)) {
                            newKeyframe.value = new Gson().fromJson(in, TimestampValue.class);
                        } else if ("realTimestamp".equals(jsonKeyframeTag)) {
                            newKeyframe.realTimestamp = in.nextInt();
                        }
                    }
                    in.endObject();

                    timeKeyframes.add(newKeyframe);
                }
                in.endArray();

            } else if ("customObjects".equals(jsonTag)) {
                set.customObjects = new Gson().fromJson(in, CustomImageObject[].class);
            }
        }
        in.endObject();

        set.positionKeyframes = positionKeyframes.toArray(new Keyframe[positionKeyframes.size()]);
        set.timeKeyframes = timeKeyframes.toArray(new Keyframe[timeKeyframes.size()]);
        sets.add(set);
    }
    in.endArray();

    return sets.toArray(new KeyframeSet[sets.size()]);
}