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

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

Introduction

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

Prototype

public void beginArray() throws IOException 

Source Link

Document

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

Usage

From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java

License:Open Source License

/**
 * This method parses the mapping between set codes and the names TCGPlayer.com uses
 *
 * @param prefAdapter The preference adapter is used to get the last update time
 * @param tcgNames    A place to store tcg names before adding to the database
 * @throws IOException Thrown if something goes wrong with the InputStream
 *//*  w w w .  j a va  2s . co m*/
public void readTCGNameJsonStream(PreferenceAdapter prefAdapter, ArrayList<NameAndMetadata> tcgNames)
        throws IOException {
    URL update;
    String label;
    String label2;
    String name = null, code = null;

    update = new URL(TCG_NAMES_URL);
    InputStreamReader isr = new InputStreamReader(update.openStream(), "ISO-8859-1");
    JsonReader reader = new JsonReader(isr);

    reader.beginObject();
    while (reader.hasNext()) {
        label = reader.nextName();

        if (label.equals("Date")) {
            String lastUpdate = prefAdapter.getLastTCGNameUpdate();
            mCurrentTCGNamePatchDate = reader.nextString();
            if (lastUpdate.equals(mCurrentTCGNamePatchDate)) {
                reader.close();
                return;
            }
        } else if (label.equals("Sets")) {
            reader.beginArray();
            while (reader.hasNext()) {
                reader.beginObject();
                while (reader.hasNext()) {
                    label2 = reader.nextName();
                    if (label2.equals("Code")) {
                        code = reader.nextString();
                    } else if (label2.equals("TCGName")) {
                        name = reader.nextString();
                    }
                }
                tcgNames.add(new NameAndMetadata(name, code));
                reader.endObject();
            }
            reader.endArray();
        }
    }
    reader.endObject();
    reader.close();
}

From source file:com.getperka.flatpack.fast.JavaDialect.java

License:Apache License

/**
 * If {@value #concreteTypeMapFile} is defined, load the file into {@link #concreteTypeMap}.
 *//*ww  w .ja  v a 2 s  . c  o m*/
private void loadConcreteTypeMap() throws IOException {
    if (baseTypeArrayFile != null) {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(baseTypeArrayFile), UTF8));
        reader.setLenient(true);
        reader.beginArray();
        while (reader.hasNext()) {
            baseTypes.add(reader.nextString());
        }
        reader.endArray();
        reader.close();
    }
}

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 .  j  a va  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.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");
    }/*from   w  w w .j a  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.gv2011.jsong.JsongAdapter.java

License:Open Source License

private JsonNode deserialize(final JsonFactoryImp jf, final JsonReader in) {
    return call(() -> {
        switch (in.peek()) {
        case STRING:
            return jf.primitive(in.nextString());
        case NUMBER:
            return jf.primitive(new BigDecimal(in.nextString()));
        case BOOLEAN:
            return jf.primitive(in.nextBoolean());
        case NULL:
            in.nextNull();/*from   w w  w .  j a va  2s  .  co m*/
            return jf.jsonNull();
        case BEGIN_ARRAY:
            in.beginArray();
            final JsonList list = XStream.fromIterator(new It(jf, in)).collect(jf.toJsonList());
            in.endArray();
            return list;
        case BEGIN_OBJECT:
            in.beginObject();
            final JsonObject obj = XStream.fromIterator(new Itm(jf, in)).collect(jf.toJsonObject());
            in.endObject();
            return obj;
        case NAME:
        case END_DOCUMENT:
        case END_OBJECT:
        case END_ARRAY:
        default:
            throw new IllegalArgumentException();
        }
    });
}

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

License:Open Source License

/**
 * Parse resources from current value/*from  w ww .java 2s.  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;//from  ww w  .j  a v  a 2s . com
    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 . j a va2  s .c  om
 *
 * @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.GeolocationResponseAdapter.java

License:Open Source License

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

    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();// w  ww. 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.samples.apps.iosched.sync.userdata.util.UserActionHelper.java

License:Open Source License

public static List<UserAction> deserializeUserActions(String str) {
    try {/*from  ww  w. j av  a 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);
    }
}