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

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

Introduction

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

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

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.
 *///from  w  ww .j  a  v  a2 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 "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;/*  w w w.j  a v a 2s .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//from   w  ww  .ja  v  a  2  s.c o m
 * @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/*  www  .  ja 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;//  ww  w.  j a  v a 2 s  .c  om
    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.
 *///from w w  w. j  a  v a 2  s. c  om
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.replaymod.replaystudio.pathing.serialize.LegacyKeyframeSetAdapter.java

License:MIT License

@SuppressWarnings("unchecked")
@Override/*  w  ww  .  ja va  2  s  .  co m*/
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()]);
}

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

License:MIT License

public Map<String, Timeline> deserialize(String serialized) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(serialized));
    Map<String, Timeline> timelines = new LinkedHashMap<>();
    reader.beginObject();//from www  .  j av  a 2s.c om
    while (reader.hasNext()) {
        Timeline timeline = registry.createTimeline();
        timelines.put(reader.nextName(), timeline);
        reader.beginArray();
        while (reader.hasNext()) {
            Path path = timeline.createPath();
            reader.beginObject();
            List<Integer> segments = new ArrayList<>();
            List<Interpolator> interpolators = new ArrayList<>();
            while (reader.hasNext()) {
                switch (reader.nextName()) {
                case "keyframes":
                    reader.beginArray();
                    while (reader.hasNext()) {
                        long time = 0;
                        Map<Property, Object> properties = new HashMap<>();
                        reader.beginObject();
                        while (reader.hasNext()) {
                            switch (reader.nextName()) {
                            case "time":
                                time = reader.nextLong();
                                break;
                            case "properties":
                                reader.beginObject();
                                while (reader.hasNext()) {
                                    String id = reader.nextName();
                                    Property property = timeline.getProperty(id);
                                    if (property == null) {
                                        throw new IOException("Unknown property: " + id);
                                    }
                                    Object value = property.fromJson(reader);
                                    properties.put(property, value);
                                }
                                reader.endObject();
                                break;
                            }
                        }
                        reader.endObject();
                        Keyframe keyframe = path.insert(time);
                        for (Map.Entry<Property, Object> entry : properties.entrySet()) {
                            keyframe.setValue(entry.getKey(), entry.getValue());
                        }
                    }
                    reader.endArray();
                    break;
                case "segments":
                    reader.beginArray();
                    while (reader.hasNext()) {
                        if (reader.peek() == JsonToken.NULL) {
                            reader.nextNull();
                            segments.add(null);
                        } else {
                            segments.add(reader.nextInt());
                        }
                    }
                    reader.endArray();
                    break;
                case "interpolators":
                    reader.beginArray();
                    while (reader.hasNext()) {
                        reader.beginObject();
                        Interpolator interpolator = null;
                        Set<String> properties = new HashSet<>();
                        while (reader.hasNext()) {
                            switch (reader.nextName()) {
                            case "type":
                                interpolator = registry.deserializeInterpolator(reader);
                                break;
                            case "properties":
                                reader.beginArray();
                                while (reader.hasNext()) {
                                    properties.add(reader.nextString());
                                }
                                reader.endArray();
                                break;
                            }
                        }
                        if (interpolator == null) {
                            throw new IOException("Missing interpolator type");
                        }
                        for (String propertyName : properties) {
                            Property property = timeline.getProperty(propertyName);
                            if (property == null) {
                                throw new IOException("Timeline does not know property '" + propertyName + "'");
                            }
                            interpolator.registerProperty(property);
                        }
                        interpolators.add(interpolator);
                        reader.endObject();
                    }
                    reader.endArray();
                    break;
                }
            }
            Iterator<Integer> iter = segments.iterator();
            for (PathSegment segment : path.getSegments()) {
                Integer next = iter.next();
                if (next != null) {
                    segment.setInterpolator(interpolators.get(next));
                }
            }
            reader.endObject();
        }
        reader.endArray();
    }
    reader.endObject();
    return timelines;
}

From source file:com.sap.core.odata.core.ep.consumer.JsonLinkConsumer.java

License:Apache License

/**
 * Reads a collection of links, optionally wrapped in a "d" object,
 * and optionally wrapped in an "results" object, where an additional "__count"
 * object could appear on the same level as the "results".
 * @param reader/*from   w  w w  .  java2  s. co m*/
 * @param entitySet
 * @return links as List of Strings
 * @throws EntityProviderException
 */
public List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet)
        throws EntityProviderException {
    List<String> links = null;
    int openedObjects = 0;

    try {
        String nextName;
        if (reader.peek() == JsonToken.BEGIN_ARRAY) {
            nextName = FormatJson.RESULTS;
        } else {
            reader.beginObject();
            openedObjects++;
            nextName = reader.nextName();
        }
        if (FormatJson.D.equals(nextName)) {
            if (reader.peek() == JsonToken.BEGIN_ARRAY) {
                nextName = FormatJson.RESULTS;
            } else {
                reader.beginObject();
                openedObjects++;
                nextName = reader.nextName();
            }
        }
        FeedMetadataImpl feedMetadata = new FeedMetadataImpl();
        if (FormatJson.COUNT.equals(nextName)) {
            JsonFeedConsumer.readInlineCount(reader, feedMetadata);
            nextName = reader.nextName();
        }
        if (FormatJson.RESULTS.equals(nextName)) {
            links = readLinksArray(reader);
        } else {
            throw new EntityProviderException(EntityProviderException.INVALID_CONTENT
                    .addContent(FormatJson.RESULTS).addContent(nextName));
        }
        if (reader.hasNext() && reader.peek() == JsonToken.NAME) {
            if (FormatJson.COUNT.equals(reader.nextName())) {
                JsonFeedConsumer.readInlineCount(reader, feedMetadata);
            } else {
                throw new EntityProviderException(EntityProviderException.INVALID_CONTENT
                        .addContent(FormatJson.COUNT).addContent(nextName));
            }
        }
        for (; openedObjects > 0; openedObjects--) {
            reader.endObject();
        }

        reader.peek(); // to assert end of document
    } catch (final IOException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    } catch (final IllegalStateException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    }

    return links;
}

From source file:com.sap.core.odata.core.ep.consumer.JsonLinkConsumer.java

License:Apache License

private List<String> readLinksArray(final JsonReader reader) throws IOException, EntityProviderException {
    List<String> links = new ArrayList<String>();

    reader.beginArray();//  ww w .  ja  v a  2 s .  c o  m
    while (reader.hasNext()) {
        reader.beginObject();
        String nextName = reader.nextName();
        if (FormatJson.URI.equals(nextName) && reader.peek() == JsonToken.STRING) {
            links.add(reader.nextString());
        } else {
            throw new EntityProviderException(
                    EntityProviderException.INVALID_CONTENT.addContent(FormatJson.URI).addContent(nextName));
        }
        reader.endObject();
    }
    reader.endArray();

    return links;
}