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.gilecode.yagson.types.TypeUtils.java

License:Apache License

private static Type readTypeAdvice(JsonReader in) throws IOException {
    in.beginObject();/* ww  w  .  ja  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;
    }//from w  w  w .  java  2  s  .c  o m
    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.filosganga.geogson.gson.PositionsAdapter.java

License:Apache License

private Positions parsePositions(JsonReader in) throws IOException {

    Optional<Positions> parsed = Optional.absent();

    if (in.peek() != JsonToken.BEGIN_ARRAY) {
        throw new IllegalArgumentException("The given json is not a valid positions");
    }/*w w w .  ja va2s .  co m*/

    in.beginArray();
    if (in.peek() == JsonToken.NUMBER) {
        parsed = Optional.of(parseSinglePosition(in));
    } else if (in.peek() == JsonToken.BEGIN_ARRAY) {
        while (in.hasNext()) {
            Positions thisPositions = parsePositions(in);
            // fix bug #30: according to the recursion (i.e. the array structure;
            // recognize that we came from a recursion because no parsed has no
            // value yet): convert the already parsed Positions to the
            // LinearPositions/AreaPositions matching the recursion level
            if (parsed.equals(Optional.absent()) && thisPositions instanceof LinearPositions) {
                AreaPositions areaPositions = new AreaPositions(
                        ImmutableList.of((LinearPositions) thisPositions));
                parsed = Optional.of((Positions) areaPositions);
            } else if (parsed.equals(Optional.absent()) && thisPositions instanceof AreaPositions) {
                MultiDimensionalPositions multiPositions = new MultiDimensionalPositions(
                        ImmutableList.of((AreaPositions) thisPositions));
                parsed = Optional.of((Positions) multiPositions);
            } else {
                // mergeFn() does all the rest, if parsed has a value
                parsed = parsed.transform(mergeFn(thisPositions)).or(Optional.of(thisPositions));
            }

        }
    }

    in.endArray();

    return parsed.orNull();
}

From source file:com.github.filosganga.geogson.gson.PositionsAdapter.java

License:Apache License

private Positions parseSinglePosition(JsonReader in) throws IOException {
    Positions parsed;/* w  ww. j ava  2s . c o  m*/
    double lon = in.nextDouble();
    double lat = in.nextDouble();
    double alt = 0.0;

    if (in.hasNext()) {
        alt = in.nextDouble();
    }

    // Skip eventual altitude or other dimensions
    while (in.peek() != JsonToken.END_ARRAY) {
        in.skipValue();
    }

    parsed = new SinglePosition(Coordinates.of(lon, lat, alt));
    return parsed;
}

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/*  www.  ja va2s  . 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//  w ww.j a  v  a  2  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 parse(String label, JsonReader r) throws Exception {
    if (!r.hasNext())
        return;/*from   w  w w . ja v a2s  . c  om*/
    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.cloud.bigquery.samples.StreamingSample.java

License:Apache License

/**
 * Run the bigquery ClI.// w w w  . ja v  a 2  s .  c o m
 *
 * @param projectId Project id
 * @param datasetId datasetid
 * @param tableId tableid
 * @param rows The source of the JSON rows we are streaming in.
 * @return Returns Iterates through the stream responses
 * @throws IOException Thrown if there is an error connecting to Bigquery.
 * @throws InterruptedException Should never be thrown
 */
// [START run]
public static Iterator<TableDataInsertAllResponse> run(final String projectId, final String datasetId,
        final String tableId, final JsonReader rows) throws IOException {

    final Bigquery bigquery = BigQueryServiceFactory.getService();
    final Gson gson = new Gson();
    rows.beginArray();

    return new Iterator<TableDataInsertAllResponse>() {

        /**
         * Check whether there is another row to stream.
         *
         * @return True if there is another row in the stream
         */
        public boolean hasNext() {
            try {
                return rows.hasNext();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        /**
         * Insert the next row, and return the response.
         *
         * @return Next page of data
         */
        public TableDataInsertAllResponse next() {
            try {
                Map<String, Object> rowData = gson.<Map<String, Object>>fromJson(rows,
                        (new HashMap<String, Object>()).getClass());
                return streamRow(bigquery, projectId, datasetId, tableId,
                        new TableDataInsertAllRequest.Rows().setJson(rowData));
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public void remove() {
            this.next();
        }
    };
}

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>/*ww w. ja v  a  2s  . co 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  ava  2  s.  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;
}