Example usage for com.google.gson.stream JsonToken NUMBER

List of usage examples for com.google.gson.stream JsonToken NUMBER

Introduction

In this page you can find the example usage for com.google.gson.stream JsonToken NUMBER.

Prototype

JsonToken NUMBER

To view the source code for com.google.gson.stream JsonToken NUMBER.

Click Source Link

Document

A JSON number represented in this API by a Java double , long , or int .

Usage

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public JsonToken peek() throws IOException {
    if (stack.isEmpty()) {
        return JsonToken.END_DOCUMENT;
    }//from w  w w  .jav  a 2  s . c o  m

    Object o = peekStack();
    if (o instanceof Iterator) {
        Object secondToTop = stack.get(stack.size() - 2);
        boolean isObject = secondToTop instanceof JsonElement && ((JsonElement) secondToTop).isJsonObject();
        Iterator<?> iterator = (Iterator<?>) o;
        if (iterator.hasNext()) {
            if (isObject) {
                return JsonToken.NAME;
            } else {
                stack.add(iterator.next());
                return peek();
            }
        } else {
            return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY;
        }
    } else if (o instanceof JsonElement) {
        JsonElement el = (JsonElement) o;
        if (el.isJsonObject()) {
            return JsonToken.BEGIN_OBJECT;
        } else if (el.isJsonArray()) {
            return JsonToken.BEGIN_ARRAY;
        } else if (el.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) o;
            if (primitive.isString()) {
                return JsonToken.STRING;
            } else if (primitive.isBoolean()) {
                return JsonToken.BOOLEAN;
            } else if (primitive.isNumber()) {
                return JsonToken.NUMBER;
            } else {
                throw new AssertionError();
            }
        } else if (el.isJsonNull()) {
            return JsonToken.NULL;
        }
        throw new AssertionError();
    } else if (o == SENTINEL_CLOSED) {
        throw new IllegalStateException("JsonReader is closed");
    } else {
        throw new AssertionError();
    }
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public String nextString() throws IOException {
    JsonToken token = peek();//from w  w  w  . ja  va  2s. co m
    if (token != JsonToken.STRING && token != JsonToken.NUMBER) {
        throw new IllegalStateException("Expected " + JsonToken.STRING + " but was " + token);
    }
    return ((JsonPrimitive) popStack()).getAsString();
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public double nextDouble() throws IOException {
    JsonToken token = peek();/* ww  w. ja  v a2 s  . c o  m*/
    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
        throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
    }
    double result = ((JsonPrimitive) peekStack()).getAsDouble();
    if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
        throw new NumberFormatException("JSON forbids NaN and infinities: " + result);
    }
    popStack();
    return result;
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public long nextLong() throws IOException {
    JsonToken token = peek();//from   ww w .  j a  v  a 2s.c  o m
    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
        throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
    }
    long result = ((JsonPrimitive) peekStack()).getAsLong();
    popStack();
    return result;
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public int nextInt() throws IOException {
    JsonToken token = peek();//from  w  w w.  j a va  2 s. c  o m
    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
        throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
    }
    int result = ((JsonPrimitive) peekStack()).getAsInt();
    popStack();
    return result;
}

From source file:com.cinchapi.concourse.util.Convert.java

License:Apache License

/**
 * Convert the next JSON object in the {@code reader} to a mapping that
 * associates each key with the Java objects that represent the
 * corresponding values./*from w w w. j  a v a2s  . c o  m*/
 * 
 * <p>
 * This method has the same rules and limitations as
 * {@link #jsonToJava(String)}. It simply uses a {@link JsonReader} to
 * handle reading an array of objects.
 * </p>
 * <p>
 * <strong>This method DOES NOT {@link JsonReader#close()} the
 * {@code reader}.</strong>
 * </p>
 * 
 * @param reader the {@link JsonReader} that contains a stream of JSON
 * @return the JSON data in the form of a {@link Multimap} from keys to
 *         values
 */
private static Multimap<String, Object> jsonToJava(JsonReader reader) {
    Multimap<String, Object> data = HashMultimap.create();
    try {
        reader.beginObject();
        JsonToken peek0;
        while ((peek0 = reader.peek()) != JsonToken.END_OBJECT) {
            String key = reader.nextName();
            peek0 = reader.peek();
            if (peek0 == JsonToken.BEGIN_ARRAY) {
                // If we have an array, add the elements individually. If
                // there are any duplicates in the array, they will be
                // filtered out by virtue of the fact that a HashMultimap
                // does not store dupes.
                reader.beginArray();
                JsonToken peek = reader.peek();
                do {
                    Object value;
                    if (peek == JsonToken.BOOLEAN) {
                        value = reader.nextBoolean();
                    } else if (peek == JsonToken.NUMBER) {
                        value = stringToJava(reader.nextString());
                    } else if (peek == JsonToken.STRING) {
                        String orig = reader.nextString();
                        value = stringToJava(orig);
                        if (orig.isEmpty()) {
                            value = orig;
                        }
                        // If the token looks like a string, it MUST be
                        // converted to a Java string unless it is a
                        // masquerading double or an instance of Thrift
                        // translatable class that has a special string
                        // representation (i.e. Tag, Link)
                        else if (orig.charAt(orig.length() - 1) != 'D'
                                && !CLASSES_WITH_ENCODED_STRING_REPR.contains(value.getClass())) {
                            value = value.toString();
                        }
                    } else if (peek == JsonToken.NULL) {
                        reader.skipValue();
                        continue;
                    } else {
                        throw new JsonParseException("Cannot parse nested object or array within an array");
                    }
                    data.put(key, value);
                } while ((peek = reader.peek()) != JsonToken.END_ARRAY);
                reader.endArray();
            } else {
                Object value;
                if (peek0 == JsonToken.BOOLEAN) {
                    value = reader.nextBoolean();
                } else if (peek0 == JsonToken.NUMBER) {
                    value = stringToJava(reader.nextString());
                } else if (peek0 == JsonToken.STRING) {
                    String orig = reader.nextString();
                    value = stringToJava(orig);
                    if (orig.isEmpty()) {
                        value = orig;
                    }
                    // If the token looks like a string, it MUST be
                    // converted to a Java string unless it is a
                    // masquerading double or an instance of Thrift
                    // translatable class that has a special string
                    // representation (i.e. Tag, Link)
                    else if (orig.charAt(orig.length() - 1) != 'D'
                            && !CLASSES_WITH_ENCODED_STRING_REPR.contains(value.getClass())) {
                        value = value.toString();
                    }
                } else if (peek0 == JsonToken.NULL) {
                    reader.skipValue();
                    continue;
                } else {
                    throw new JsonParseException("Cannot parse nested object to value");
                }
                data.put(key, value);
            }
        }
        reader.endObject();
        return data;
    } catch (IOException | IllegalStateException e) {
        throw new JsonParseException(e.getMessage());
    }
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

License:Open Source License

public static <T> int readJsnArr(JsonReader reader, String tableName, Class<T> clazz)
        throws IOException, JSONException, Exception {
    JSONObject o = new JSONObject();
    JsonToken peek = reader.peek();/* www.  jav  a2s  . c  o m*/
    String n = null;
    reader.beginArray();
    int j = 0;
    int i = 0;
    while (reader.hasNext()) {
        peek = reader.peek();
        if (reader.peek() == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
        } else if (reader.peek() == JsonToken.END_OBJECT) {
            reader.endObject();
        }
        o = new JSONObject();
        while (reader.hasNext()) {
            peek = reader.peek();
            if (peek == JsonToken.NAME) {
                n = reader.nextName();
            } else if (peek == JsonToken.BEGIN_OBJECT) {
                reader.beginObject();
            } else if (peek == JsonToken.END_OBJECT) {
                reader.endObject();
            } else if (peek == JsonToken.BOOLEAN) {
                try {
                    o.put(n, reader.nextBoolean());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            } else if (peek == JsonToken.STRING) {
                try {
                    o.put(n, reader.nextString());

                } catch (JSONException e) {

                    e.printStackTrace();
                }
            } else if (peek == JsonToken.NUMBER) {
                try {
                    o.put(n, reader.nextDouble());

                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        }
        reader.endObject();
        if (o.has("key")) {
            i = i + 1;
            j = j + 1;
            if (j % 100 == 0) {
                j = 2;
            }
            saveEntityFromJson(o, tableName, clazz, i);
            if (i % 10 == 0) {
                //notifyUser(context.getString(R.string.flowzr_sync_receiving) + " " + tableName + ". " + context.getString(R.string.hint_run_background), (int)(Math.round(j)));
            }
        }
    }
    reader.endArray();
    return i;
}

From source file:com.gd.misc.test.JsonReader.java

License:Apache License

/**
 * Returns the type of the next token without consuming it.
 *///from   www .  jav a  2  s  .com
public JsonToken peek() throws IOException {
    int p = peeked;
    if (p == PEEKED_NONE) {
        p = doPeek();
    }

    switch (p) {
    case PEEKED_BEGIN_OBJECT:
        return JsonToken.BEGIN_OBJECT;
    case PEEKED_END_OBJECT:
        return JsonToken.END_OBJECT;
    case PEEKED_BEGIN_ARRAY:
        return JsonToken.BEGIN_ARRAY;
    case PEEKED_END_ARRAY:
        return JsonToken.END_ARRAY;
    case PEEKED_SINGLE_QUOTED_NAME:
    case PEEKED_DOUBLE_QUOTED_NAME:
    case PEEKED_UNQUOTED_NAME:
        return JsonToken.NAME;
    case PEEKED_TRUE:
    case PEEKED_FALSE:
        return JsonToken.BOOLEAN;
    case PEEKED_NULL:
        return JsonToken.NULL;
    case PEEKED_SINGLE_QUOTED:
    case PEEKED_DOUBLE_QUOTED:
    case PEEKED_UNQUOTED:
    case PEEKED_BUFFERED:
        return JsonToken.STRING;
    case PEEKED_LONG:
    case PEEKED_NUMBER:
        return JsonToken.NUMBER;
    case PEEKED_EOF:
        return JsonToken.END_DOCUMENT;
    default:
        throw new AssertionError();
    }
}

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  a2s .  com*/
     * 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 .ja  va2 s  .  c  o 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();
}