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

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

Introduction

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

Prototype

JsonToken END_OBJECT

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

Click Source Link

Document

The closing of a JSON object.

Usage

From source file:BundleTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from   w  w  w  .  j  a va  2 s  .com
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    if (!Bundle.class.isAssignableFrom(type.getRawType())) {
        return null;
    }
    return (TypeAdapter<T>) new TypeAdapter<Bundle>() {
        @Override
        public void write(JsonWriter out, Bundle bundle) throws IOException {
            if (bundle == null) {
                out.nullValue();
                return;
            }
            out.beginObject();
            for (String key : bundle.keySet()) {
                out.name(key);
                Object value = bundle.get(key);
                if (value == null) {
                    out.nullValue();
                } else {
                    gson.toJson(value, value.getClass(), out);
                }
            }
            out.endObject();
        }

        @Override
        public Bundle read(JsonReader in) throws IOException {
            switch (in.peek()) {
            case NULL:
                in.nextNull();
                return null;
            case BEGIN_OBJECT:
                return toBundle(readObject(in));
            default:
                throw new IOException("expecting object: " + in.getPath());
            }
        }

        private Bundle toBundle(List<Pair<String, Object>> values) throws IOException {
            Bundle bundle = new Bundle();
            for (Pair<String, Object> entry : values) {
                String key = entry.first;
                Object value = entry.second;
                if (value instanceof String) {
                    bundle.putString(key, (String) value);
                } else if (value instanceof Integer) {
                    bundle.putInt(key, ((Integer) value).intValue());
                } else if (value instanceof Long) {
                    bundle.putLong(key, ((Long) value).longValue());
                } else if (value instanceof Double) {
                    bundle.putDouble(key, ((Double) value).doubleValue());
                } else if (value instanceof Parcelable) {
                    bundle.putParcelable(key, (Parcelable) value);
                } else if (value instanceof List) {
                    List<Pair<String, Object>> objectValues = (List<Pair<String, Object>>) value;
                    Bundle subBundle = toBundle(objectValues);
                    bundle.putParcelable(key, subBundle);
                } else {
                    throw new IOException("Unparcelable key, value: " + key + ", " + value);
                }
            }
            return bundle;
        }

        private List<Pair<String, Object>> readObject(JsonReader in) throws IOException {
            List<Pair<String, Object>> object = new ArrayList<Pair<String, Object>>();
            in.beginObject();
            while (in.peek() != JsonToken.END_OBJECT) {
                switch (in.peek()) {
                case NAME:
                    String name = in.nextName();
                    Object value = readValue(in);
                    object.add(new Pair<String, Object>(name, value));
                    break;
                case END_OBJECT:
                    break;
                default:
                    throw new IOException("expecting object: " + in.getPath());
                }
            }
            in.endObject();
            return object;
        }

        private Object readValue(JsonReader in) throws IOException {
            switch (in.peek()) {
            case BEGIN_ARRAY:
                return readArray(in);
            case BEGIN_OBJECT:
                return readObject(in);
            case BOOLEAN:
                return in.nextBoolean();
            case NULL:
                in.nextNull();
                return null;
            case NUMBER:
                return readNumber(in);
            case STRING:
                return in.nextString();
            default:
                throw new IOException("expecting value: " + in.getPath());
            }
        }

        private Object readNumber(JsonReader in) throws IOException {
            double doubleValue = in.nextDouble();
            if (doubleValue - Math.ceil(doubleValue) == 0) {
                long longValue = (long) doubleValue;
                if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
                    return (int) longValue;
                }
                return longValue;
            }
            return doubleValue;
        }

        @SuppressWarnings("rawtypes")
        private List readArray(JsonReader in) throws IOException {
            List list = new ArrayList();
            in.beginArray();
            while (in.peek() != JsonToken.END_ARRAY) {
                Object element = readValue(in);
                list.add(element);
            }
            in.endArray();
            return list;
        }
    };
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public void endObject() throws IOException {
    expect(JsonToken.END_OBJECT);
    popStack(); // empty iterator
    popStack(); // object
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public boolean hasNext() throws IOException {
    JsonToken token = peek();/*from   www .j a  v  a 2s  .co m*/
    return token != JsonToken.END_OBJECT && token != JsonToken.END_ARRAY;
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public JsonToken peek() throws IOException {
    if (stack.isEmpty()) {
        return JsonToken.END_DOCUMENT;
    }/*ww  w.j  a  va 2 s  . com*/

    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:co.cask.cdap.format.StructuredRecordStringConverter.java

License:Apache License

private static Map<Object, Object> readMap(JsonReader reader, Map.Entry<Schema, Schema> mapSchema)
        throws IOException {
    Schema keySchema = mapSchema.getKey();
    if (!keySchema.isCompatible(Schema.of(Schema.Type.STRING))) {
        throw new IOException("Complex key type not supported: " + keySchema);
    }//from w  w  w .j a va  2 s  .c o m

    Schema valueSchema = mapSchema.getValue();
    Map<Object, Object> result = new HashMap<>();

    reader.beginObject();
    while (reader.peek() != JsonToken.END_OBJECT) {
        Object key = convertKey(reader.nextName(), keySchema.getType());
        result.put(key, readJson(reader, valueSchema));
    }
    reader.endObject();

    return result;
}

From source file:co.cask.cdap.format.StructuredRecordStringConverter.java

License:Apache License

private static StructuredRecord readRecord(JsonReader reader, Schema schema) throws IOException {
    StructuredRecord.Builder builder = StructuredRecord.builder(schema);

    reader.beginObject();// w  ww . j  a  v  a 2  s  .  com
    while (reader.peek() != JsonToken.END_OBJECT) {
        Schema.Field field = schema.getField(reader.nextName());
        if (field == null) {
            // Ignore unrecognized fields
            reader.skipValue();
            continue;
        }

        builder.set(field.getName(), readJson(reader, field.getSchema()));
    }
    reader.endObject();

    return builder.build();
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

@NonNull
static Map<SourceFile, Map<SourcePosition, SourceFilePosition>> loadFromMultiFile(@NonNull File folder,
        @NonNull String shard) {/*  w  w  w.j  ava 2s  .  co  m*/
    Map<SourceFile, Map<SourcePosition, SourceFilePosition>> map = Maps.newConcurrentMap();
    JsonReader reader;
    File file = getMultiFile(folder, shard);
    if (!file.exists()) {
        return map;
    }
    try {
        reader = new JsonReader(Files.newReader(file, Charsets.UTF_8));
    } catch (FileNotFoundException e) {
        // Shouldn't happen unless it disappears under us.
        return map;
    }
    try {
        reader.beginArray();
        while (reader.peek() != JsonToken.END_ARRAY) {
            reader.beginObject();
            SourceFile toFile = SourceFile.UNKNOWN;
            Map<SourcePosition, SourceFilePosition> innerMap = Maps.newLinkedHashMap();
            while (reader.peek() != JsonToken.END_OBJECT) {
                final String name = reader.nextName();
                if (name.equals(KEY_OUTPUT_FILE)) {
                    toFile = mSourceFileJsonTypeAdapter.read(reader);
                } else if (name.equals(KEY_MAP)) {
                    reader.beginArray();
                    while (reader.peek() != JsonToken.END_ARRAY) {
                        reader.beginObject();
                        SourceFilePosition from = null;
                        SourcePosition to = null;
                        while (reader.peek() != JsonToken.END_OBJECT) {
                            final String innerName = reader.nextName();
                            if (innerName.equals(KEY_FROM)) {
                                from = mSourceFilePositionJsonTypeAdapter.read(reader);
                            } else if (innerName.equals(KEY_TO)) {
                                to = mSourcePositionJsonTypeAdapter.read(reader);
                            } else {
                                throw new IOException(String.format("Unexpected property: %s", innerName));
                            }
                        }
                        if (from == null || to == null) {
                            throw new IOException("Each record must contain both from and to.");
                        }
                        innerMap.put(to, from);
                        reader.endObject();
                    }
                    reader.endArray();
                } else {
                    throw new IOException(String.format("Unexpected property: %s", name));
                }
            }
            map.put(toFile, innerMap);
            reader.endObject();
        }
        reader.endArray();
        return map;
    } catch (IOException e) {
        // TODO: trigger a non-incremental merge if this happens.
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (Throwable e2) {
            // well, we tried.
        }
    }
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

@NonNull
static Map<SourceFile, SourceFile> loadFromSingleFile(@NonNull File folder, @NonNull String shard) {
    Map<SourceFile, SourceFile> fileMap = Maps.newConcurrentMap();
    JsonReader reader;//from ww  w.  j ava 2s . com
    File file = getSingleFile(folder, shard);
    if (!file.exists()) {
        return fileMap;
    }
    try {
        reader = new JsonReader(Files.newReader(file, Charsets.UTF_8));
    } catch (FileNotFoundException e) {
        // Shouldn't happen unless it disappears under us.
        return fileMap;
    }
    try {
        reader.beginArray();
        while (reader.peek() != JsonToken.END_ARRAY) {
            reader.beginObject();
            SourceFile merged = SourceFile.UNKNOWN;
            SourceFile source = SourceFile.UNKNOWN;
            while (reader.peek() != JsonToken.END_OBJECT) {
                String name = reader.nextName();
                if (name.equals(KEY_MERGED)) {
                    merged = mSourceFileJsonTypeAdapter.read(reader);
                } else if (name.equals(KEY_SOURCE)) {
                    source = mSourceFileJsonTypeAdapter.read(reader);
                } else {
                    throw new IOException(String.format("Unexpected property: %s", name));
                }
            }
            reader.endObject();
            fileMap.put(merged, source);
        }
        reader.endArray();
        return fileMap;
    } catch (IOException e) {
        // TODO: trigger a non-incremental merge if this happens.
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (Throwable e) {
            // well, we tried.
        }
    }
}

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  .ja v  a2s.  com
 * 
 * <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 readMessage(JsonReader reader, String tableName, Class<T> clazz, long last_sync_ts)
        throws IOException, JSONException, Exception {
    String n = null;//from w  ww.  j a v  a2s  .c om
    int i = 0;

    while (reader.hasNext()) {
        JsonToken peek = reader.peek();

        String v = null;
        if (peek == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
        } else if (peek == JsonToken.NAME) {
            n = reader.nextName();
        } else if (peek == JsonToken.BEGIN_ARRAY) {
            if (n.equals(tableName)) {
                i = readJsnArr(reader, tableName, clazz);

            } else {
                if (n.equals("params")) {
                    reader.beginArray();
                    if (reader.hasNext()) {
                        reader.beginObject();
                        if (reader.hasNext()) {
                            n = reader.nextName();
                            v = reader.nextString();
                        }
                        reader.endObject();
                    }
                    reader.endArray();
                } else {
                    reader.skipValue();
                }
            }
        } else if (peek == JsonToken.END_OBJECT) {
            reader.endObject();
        } else if (peek == JsonToken.END_ARRAY) {
            reader.endArray();
        } else if (peek == JsonToken.STRING) {
            reader.skipValue();
        } else {
            reader.skipValue();
        }
    }
    return i;
}