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

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

Introduction

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

Prototype

public String nextName() throws IOException 

Source Link

Document

Returns the next token, a com.google.gson.stream.JsonToken#NAME property name , and consumes it.

Usage

From source file:com.getperka.flatpack.Unpacker.java

License:Apache License

private <T> FlatPackEntity<T> unpack(Type returnType, JsonReader reader, Principal principal)
        throws IOException {
    // Hold temporary state for deserialization
    DeserializationContext context = contexts.get();

    /*/* w  w  w .  jav  a 2 s.  c o  m*/
     * Decoding is done as a two-pass operation since the runtime type of an allocated object cannot
     * be swizzled. The per-entity data is held as a semi-reified JsonObject to be passed off to a
     * Codex.
     */
    Map<HasUuid, JsonObject> entityData = FlatPackCollections.mapForIteration();
    // Used to populate the entityData map
    JsonParser jsonParser = new JsonParser();
    /*
     * The reader is placed in lenient mode as an aid to developers, however all output will be
     * strictly formatted.
     */
    reader.setLenient(true);

    // The return value
    @SuppressWarnings("unchecked")
    FlatPackEntity<T> toReturn = (FlatPackEntity<T>) FlatPackEntity.create(returnType, null, principal);
    // Stores the single, top-level value in the payload for two-pass reification
    JsonElement value = null;

    if (reader.peek().equals(JsonToken.NULL)) {
        return toReturn;
    }

    reader.beginObject();

    while (JsonToken.NAME.equals(reader.peek())) {
        String name = reader.nextName();
        if ("data".equals(name)) {
            // data : { "fooEntity" : [ { ... }, { ... } ]
            reader.beginObject();
            while (JsonToken.NAME.equals(reader.peek())) {
                // Turn "fooEntity" into the actual FooEntity class
                String simpleName = reader.nextName();
                Class<? extends HasUuid> clazz = typeContext.getClass(simpleName);
                if (clazz == null) {
                    if (ignoreUnresolvableTypes) {
                        reader.skipValue();
                        continue;
                    } else {
                        throw new UnsupportedOperationException("Cannot resolve type " + simpleName);
                    }
                } else if (Modifier.isAbstract(clazz.getModifiers())) {
                    throw new UnsupportedOperationException(
                            "A subclass of " + simpleName + " must be used instead");
                }
                context.pushPath("allocating " + simpleName);
                try {
                    // Find the Codex for the requested entity type
                    EntityCodex<?> codex = (EntityCodex<?>) typeContext.getCodex(clazz);

                    // Take the n-many property objects and stash them for later decoding
                    reader.beginArray();
                    while (!JsonToken.END_ARRAY.equals(reader.peek())) {
                        JsonObject chunk = jsonParser.parse(reader).getAsJsonObject();
                        HasUuid entity = codex.allocate(chunk, context);
                        toReturn.addExtraEntity(entity);
                        entityData.put(entity, chunk.getAsJsonObject());
                    }
                    reader.endArray();
                } finally {
                    context.popPath();
                }
            }
            reader.endObject();
        } else if ("errors".equals(name)) {
            // "errors" : { "path" : "problem", "path2" : "problem2" }
            reader.beginObject();
            while (JsonToken.NAME.equals(reader.peek())) {
                String path = reader.nextName();
                if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) {
                    toReturn.addError(path, reader.nextString());
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } else if ("metadata".equals(name)) {
            reader.beginArray();

            while (!JsonToken.END_ARRAY.equals(reader.peek())) {
                EntityMetadata meta = new EntityMetadata();
                JsonObject metaElement = jsonParser.parse(reader).getAsJsonObject();
                metaCodex.get().readProperties(meta, metaElement, context);
                toReturn.addMetadata(meta);
            }

            reader.endArray();
        } else if ("value".equals(name)) {
            // Just stash the value element in case it occurs first
            value = jsonParser.parse(reader);
        } else if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) {
            // Save off any other simple properties
            toReturn.putExtraData(name, reader.nextString());
        } else {
            // Ignore random other entries
            reader.skipValue();
        }
    }

    reader.endObject();
    reader.close();

    for (Map.Entry<HasUuid, JsonObject> entry : entityData.entrySet()) {
        HasUuid entity = entry.getKey();
        EntityCodex<HasUuid> codex = (EntityCodex<HasUuid>) typeContext.getCodex(entity.getClass());
        codex.readProperties(entity, entry.getValue(), context);
    }

    @SuppressWarnings("unchecked")
    Codex<T> returnCodex = (Codex<T>) typeContext.getCodex(toReturn.getType());
    toReturn.withValue(returnCodex.read(value, context));

    for (Map.Entry<UUID, String> entry : context.getWarnings().entrySet()) {
        toReturn.addWarning(entry.getKey().toString(), entry.getValue());
    }

    // Process metadata
    for (EntityMetadata meta : toReturn.getMetadata()) {
        if (meta.isPersistent()) {
            HasUuid entity = context.getEntity(meta.getUuid());
            if (entity instanceof PersistenceAware) {
                ((PersistenceAware) entity).markPersistent();
            }
        }
    }

    context.runPostWork();
    context.close();

    return toReturn;
}

From source file:com.gilecode.yagson.types.TypeUtils.java

License:Apache License

private static Type readTypeAdvice(JsonReader in) throws IOException {
    in.beginObject();/*from   w ww. j  a  va  2s .c om*/
    if (!in.hasNext()) {
        throw new JsonSyntaxException("BEGIN_OBJECT is not expected at path " + in.getPath());
    }
    String name = in.nextName();
    if (!name.equals("@type")) {
        throw new JsonSyntaxException("@type is expected at path " + in.getPath());
    }
    return readTypeAdviceAfterTypeField(in);
}

From source file:com.gilecode.yagson.types.TypeUtils.java

License:Apache License

private static boolean consumeValueField(JsonReader in) throws IOException {
    if (!in.hasNext()) {
        // no @val means actually null value, e.g. skipped by serialization
        return false;
    }/* w  w  w  .  j  a v  a2  s.  c om*/
    String name = in.nextName();
    if (!name.equals("@val")) {
        throw new JsonSyntaxException("Only @type and @val fields are expected at the type advice "
                + "objects at path " + in.getPath());
    }
    return true;
}

From source file:com.github.kevinsawicki.halligan.Resource.java

License:Open Source License

/**
 * Fill this resource by parsing the next object in the reader
 *
 * @param reader//from ww  w .  j ava  2  s  .c  om
 * @return this resource
 * @throws IOException
 */
protected Resource parse(final JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext() && reader.peek() == NAME) {
        String name = reader.nextName();
        if ("_links".equals(name))
            parseLinks(reader);
        else if ("_embedded".equals(name))
            parseResources(reader);
        else
            parseProperty(reader, name);
    }
    reader.endObject();
    return this;
}

From source file:com.github.kevinsawicki.halligan.Resource.java

License:Open Source License

/**
 * Parse resources from current value/*from  w  w w. j  av a2  s .  com*/
 *
 * @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 parseObject(String label, JsonReader r) throws Exception {

    w.writeStartElement(NS, "object");
    if (label != null)
        w.writeAttribute("name", label);
    for (;;) {//from   w  w  w .j a v  a  2s  .c o m
        if (r.peek() == JsonToken.END_OBJECT)
            break;
        if (r.peek() != JsonToken.NAME)
            throw new IllegalStateException(r.peek().name());
        String s = r.nextName();
        parse(s, r);
    }
    w.writeEndElement();
    r.endObject();
}

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   w  ww. j  a 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>/*from w  ww  . ja  v  a  2  s .c om*/
 * {
 *   "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>/* www  .jav a2  s.  c  o m*/
 * {
 *   "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  www . j  a  v a 2 s.  c om*/
 *   "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;
}