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.github.kevinsawicki.halligan.Resource.java

License:Open Source License

/**
 * Parse resources from current value/*w w w.ja  v  a2  s .  c  om*/
 *
 * @param reader
 * @throws IOException
 */
protected void parseResources(final JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        JsonToken next = reader.peek();
        switch (next) {
        case BEGIN_OBJECT:
            resources.put(name, Collections.singletonList(createResource().parse(reader)));
            break;
        case BEGIN_ARRAY:
            reader.beginArray();
            List<Resource> entries = new ArrayList<Resource>();
            while (reader.peek() == BEGIN_OBJECT)
                entries.add(createResource().parse(reader));
            reader.endArray();
            resources.put(name, entries);
            break;
        default:
            throw new IOException(
                    "_embedded object value is a " + next.name() + " and must be an array or object");
        }
    }
    reader.endObject();
}

From source file:com.github.lindenb.gatkui.Json2Xml.java

License:Open Source License

private void parse(String label, JsonReader r) throws Exception {
    if (!r.hasNext())
        return;// www  .j  a  v a 2s  .  c  o m
    JsonToken token = r.peek();
    switch (token) {
    case NAME:
        break;
    case BEGIN_OBJECT: {
        r.beginObject();
        parseObject(label, r);
        break;
    }
    case END_OBJECT: {
        break;
    }
    case BEGIN_ARRAY: {
        r.beginArray();
        parseArray(label, r);
        break;
    }
    case END_ARRAY: {
        break;
    }
    case NULL: {
        r.nextNull();
        w.writeEmptyElement(NS, "null");
        if (label != null)
            w.writeAttribute("name", label);
        break;
    }
    case STRING: {
        w.writeStartElement(NS, "string");
        if (label != null)
            w.writeAttribute("name", label);
        w.writeCharacters(r.nextString());
        w.writeEndElement();
        break;
    }
    case NUMBER: {
        w.writeStartElement(NS, "number");
        if (label != null)
            w.writeAttribute("name", label);
        String s;
        try {
            s = String.valueOf(r.nextLong());
        } catch (Exception err) {
            s = String.valueOf(r.nextDouble());
        }

        w.writeCharacters(s);
        w.writeEndElement();
        break;
    }
    case BOOLEAN: {
        w.writeStartElement(NS, "boolean");
        if (label != null)
            w.writeAttribute("name", label);
        w.writeCharacters(String.valueOf(r.nextBoolean()));
        w.writeEndElement();
        break;
    }
    case END_DOCUMENT: {
        break;
    }
    default:
        throw new IllegalStateException(token.name());
    }

}

From source file:com.google.maps.internal.DateTimeAdapter.java

License:Open Source License

/**
 * Read a Time object from a Directions API result and convert it to a {@link DateTime}.
 *
 * <p>We are expecting to receive something akin to the following:
 * <pre>//from ww  w  . ja  v a  2 s  . c o m
 * {
 *   "text" : "4:27pm",
 *   "time_zone" : "Australia/Sydney",
 *   "value" : 1406528829
 * }
 * </pre>
 */
@Override
public DateTime read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    String timeZoneId = "";
    long secondsSinceEpoch = 0L;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("text")) {
            // Ignore the human readable rendering.
            reader.nextString();
        } else if (name.equals("time_zone")) {
            timeZoneId = reader.nextString();
        } else if (name.equals("value")) {
            secondsSinceEpoch = reader.nextLong();
        }

    }
    reader.endObject();

    return new DateTime(secondsSinceEpoch * 1000, DateTimeZone.forID(timeZoneId));
}

From source file:com.google.maps.internal.DistanceAdapter.java

License:Open Source License

/**
 * Read a distance object from a Directions API result and convert it to a {@link Distance}.
 *
 * <p>We are expecting to receive something akin to the following:
 * <pre>//www .j ava2s  .c  o m
 * {
 *   "value": 207,
     "text": "0.1 mi"
 * }
 * </pre>
 */
@Override
public Distance read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    Distance distance = new Distance();

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("text")) {
            distance.humanReadable = reader.nextString();
        } else if (name.equals("value")) {
            distance.inMeters = reader.nextLong();
        }

    }
    reader.endObject();

    return distance;
}

From source file:com.google.maps.internal.DurationAdapter.java

License:Open Source License

/**
 * Read a distance object from a Directions API result and convert it to a {@link Distance}.
 *
 * <p>We are expecting to receive something akin to the following:
 * <pre>/*  w w w.  j a v  a  2 s.com*/
 * {
 *   "value": 207,
     "text": "0.1 mi"
 * }
 * </pre>
 */
@Override
public Duration read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    Duration duration = new Duration();

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("text")) {
            duration.humanReadable = reader.nextString();
        } else if (name.equals("value")) {
            duration.inSeconds = reader.nextLong();
        }

    }
    reader.endObject();

    return duration;
}

From source file:com.google.maps.internal.FareAdapter.java

License:Open Source License

/**
 * Read a Fare object from the Directions API and convert to a {@link com.google.maps.model.Fare}
 *
 * <pre>{//from   w w  w .j a v a  2s .c o  m
 *   "currency": "USD",
 *   "value": 6
 * }</pre>
 */
@Override
public Fare read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    Fare fare = new Fare();
    reader.beginObject();
    while (reader.hasNext()) {
        String key = reader.nextName();
        if ("currency".equals(key)) {
            fare.currency = Currency.getInstance(reader.nextString());
        } else if ("value".equals(key)) {
            // this relies on nextString() being able to coerce raw numbers to strings
            fare.value = new BigDecimal(reader.nextString());
        } else {
            // Be forgiving of unexpected values
            reader.skipValue();
        }
    }
    reader.endObject();

    return fare;
}

From source file:com.google.maps.internal.GeolocationResponseAdapter.java

License:Open Source License

@Override
public GeolocationApi.Response read(JsonReader reader) throws IOException {

    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();/*from  w w  w. ja  va  2 s . c  om*/
        return null;
    }
    GeolocationApi.Response response = new GeolocationApi.Response();
    LatLngAdapter latLngAdapter = new LatLngAdapter();

    reader.beginObject(); // opening {
    while (reader.hasNext()) {
        String name = reader.nextName();
        // two different objects could be returned a success object containing "location" and "accuracy"
        // keys or an error object containing an "error" key
        if (name.equals("location")) {
            // we already have a parser for the LatLng object so lets use that
            response.location = latLngAdapter.read(reader);
        } else if (name.equals("accuracy")) {
            response.accuracy = reader.nextDouble();
        } else if (name.equals("error")) {
            reader.beginObject(); // the error key leads to another object...
            while (reader.hasNext()) {
                String errName = reader.nextName();
                // ...with keys "errors", "code" and "message"
                if (errName.equals("code")) {
                    response.code = reader.nextInt();
                } else if (errName.equals("message")) {
                    response.message = reader.nextString();
                } else if (errName.equals("errors")) {
                    reader.beginArray(); // its plural because its an array of errors...
                    while (reader.hasNext()) {
                        reader.beginObject();// ...and each error array element is an object...
                        while (reader.hasNext()) {
                            errName = reader.nextName();
                            // ...with keys "reason", "domain", "debugInfo", "location", "locationType",  and "message" (again)
                            if (errName.equals("reason")) {
                                response.reason = reader.nextString();
                            } else if (errName.equals("domain")) {
                                response.domain = reader.nextString();
                            } else if (errName.equals("debugInfo")) {
                                response.debugInfo = reader.nextString();
                            } else if (errName.equals("message")) {
                                // have this already
                                reader.nextString();
                            } else if (errName.equals("location")) {
                                reader.nextString();
                            } else if (errName.equals("locationType")) {
                                reader.nextString();
                            }
                        }
                        reader.endObject();
                    }
                    reader.endArray();
                }
            }
            reader.endObject(); // closing }
        }
    }
    reader.endObject();
    return response;
}

From source file:com.google.maps.internal.LatLngAdapter.java

License:Open Source License

/**
 * Reads in a JSON object and try to create a LatLng in one of the following formats.
 *
 * <pre>{/*from   w  w  w.  j  av a 2s .  c o m*/
 *   "lat" : -33.8353684,
 *   "lng" : 140.8527069
 * }
 *
 * {
 *   "latitude": -33.865257570508334,
 *   "longitude": 151.19287000481452
 * }</pre>
 */
@Override
public LatLng read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    double lat = 0;
    double lng = 0;
    boolean hasLat = false;
    boolean hasLng = false;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if ("lat".equals(name) || "latitude".equals(name)) {
            lat = reader.nextDouble();
            hasLat = true;
        } else if ("lng".equals(name) || "longitude".equals(name)) {
            lng = reader.nextDouble();
            hasLng = true;
        }
    }
    reader.endObject();

    if (hasLat && hasLng) {
        return new LatLng(lat, lng);
    } else {
        return null;
    }
}

From source file:com.google.samples.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  ww  . j  a  va  2s .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 {
                LOGW(TAG, "Skipping unknown key in conference data json: " + key);
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserActionHelper.java

License:Open Source License

public static List<UserAction> deserializeUserActions(String str) {
    try {/*from ww w .  ja  va  2 s .  co  m*/
        ArrayList<UserAction> actions = new ArrayList<UserAction>();
        JsonReader reader = new JsonReader(new StringReader(str));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            UserAction action = new UserAction();
            while (reader.hasNext()) {
                String key = reader.nextName();
                if ("type".equals(key)) {
                    action.type = UserAction.TYPE.valueOf(reader.nextString());
                } else if ("id".equals(key)) {
                    action.sessionId = reader.nextString();
                } else {
                    throw new RuntimeException("Invalid key " + key + " in serialized UserAction: " + str);
                }
            }
            reader.endObject();
            actions.add(action);
        }
        reader.endArray();
        return actions;
    } catch (IOException ex) {
        throw new RuntimeException("Error deserializing UserActions: " + str, ex);
    }
}