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

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

Introduction

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

Prototype

public JsonToken peek() throws IOException 

Source Link

Document

Returns the type of the next token without consuming it.

Usage

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

License:Apache License

@Override
public Message read(JsonReader in) throws IOException {
    in.beginObject();/*  w w  w  . java2  s  .co  m*/
    Message.Kind kind = Message.Kind.UNKNOWN;
    String text = "";
    String rawMessage = null;
    ImmutableList.Builder<SourceFilePosition> positions = new ImmutableList.Builder<SourceFilePosition>();
    SourceFile legacyFile = SourceFile.UNKNOWN;
    SourcePosition legacyPosition = SourcePosition.UNKNOWN;
    while (in.hasNext()) {
        String name = in.nextName();
        if (name.equals(KIND)) {
            //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
            Message.Kind theKind = KIND_STRING_ENUM_MAP.inverse().get(in.nextString().toLowerCase());
            kind = (theKind != null) ? theKind : Message.Kind.UNKNOWN;
        } else if (name.equals(TEXT)) {
            text = in.nextString();
        } else if (name.equals(RAW_MESSAGE)) {
            rawMessage = in.nextString();
        } else if (name.equals(SOURCE_FILE_POSITIONS)) {
            switch (in.peek()) {
            case BEGIN_ARRAY:
                in.beginArray();
                while (in.hasNext()) {
                    positions.add(mSourceFilePositionTypeAdapter.read(in));
                }
                in.endArray();
                break;
            case BEGIN_OBJECT:
                positions.add(mSourceFilePositionTypeAdapter.read(in));
                break;
            default:
                in.skipValue();
                break;
            }
        } else if (name.equals(LEGACY_SOURCE_PATH)) {
            legacyFile = new SourceFile(new File(in.nextString()));
        } else if (name.equals(LEGACY_POSITION)) {
            legacyPosition = mSourcePositionTypeAdapter.read(in);
        } else {
            in.skipValue();
        }
    }
    in.endObject();

    if (legacyFile != SourceFile.UNKNOWN || legacyPosition != SourcePosition.UNKNOWN) {
        positions.add(new SourceFilePosition(legacyFile, legacyPosition));
    }
    if (rawMessage == null) {
        rawMessage = text;
    }
    ImmutableList<SourceFilePosition> sourceFilePositions = positions.build();
    if (!sourceFilePositions.isEmpty()) {
        return new Message(kind, text, rawMessage, sourceFilePositions);
    } else {
        return new Message(kind, text, rawMessage, ImmutableList.of(SourceFilePosition.UNKNOWN));
    }
}

From source file:com.antew.redditinpictures.library.gson.VoteAdapter.java

License:Apache License

@Override
public Vote read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();/*w  ww .ja v  a  2 s . co  m*/
        return Vote.NEUTRAL;
    }

    return reader.nextBoolean() ? Vote.UP : Vote.DOWN;
}

From source file:com.atlauncher.workers.EnumTypeAdapterFactory.java

License:Creative Commons License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum())
        return null;
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }//from w  ww.j a v a 2  s. c  o m

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null)
                return null;
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:com.bzcentre.dapiPush.ReceipientTypeAdapter.java

License:Open Source License

@Override
public Receipient read(JsonReader in)
        throws IOException, IllegalStateException, JsonParseException, NumberFormatException {
    NginxClojureRT.log.debug(TAG + " invoked...");
    Receipient receipient = new Receipient();
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/*from  w w  w . jav a 2 s.  co  m*/
        return null;
    }

    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
        case "apns_token":
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
            } else
                receipient.setApns_Token(in.nextString());
            break;
        case "fcm_token":
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
            } else
                receipient.setFcm_Token(in.nextString());
            break;
        case "payload":
            receipient.setPayload(extractPayload(in));
            break;
        }
    }
    in.endObject();

    NginxClojureRT.log.debug(TAG + "Deserializing and adding receipient of "
            + (receipient.getApns_Token() == null ? "fcm--" + receipient.getFcm_Token()
                    : "apns--" + receipient.getApns_Token()));
    return receipient;
}

From source file:com.bzcentre.dapiPush.ReceipientTypeAdapter.java

License:Open Source License

private MeetingPayload extractPayload(JsonReader in)
        throws IOException, NumberFormatException, IllegalStateException, JsonParseException {
    NginxClojureRT.log.debug(TAG + "TypeAdapter extracting Payload...");

    MeetingPayload meetingPayload = new MeetingPayload();
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/* w  ww . j ava  2 s.  c o  m*/
        throw new JsonParseException("null Payload");
    }

    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
        case "aps":
            in.beginObject();
            while (in.hasNext()) {
                switch (in.nextName()) {
                case "badge":
                    meetingPayload.getAps().setBadge(in.nextLong());
                    break;
                case "sound":
                    meetingPayload.getAps().setSound(in.nextString());
                    break;
                case "alert":
                    in.beginObject();
                    while (in.hasNext()) {
                        switch (in.nextName()) {
                        case "title":
                            meetingPayload.getAps().getAlert().setTitle(in.nextString());
                            break;
                        case "body":
                            meetingPayload.getAps().getAlert().setBody(in.nextString());
                            break;
                        case "action-loc-key":
                            meetingPayload.getAps().getAlert().setActionLocKey(in.nextString());
                            break;
                        }
                    }
                    in.endObject();
                    break;
                }
            }
            in.endObject();
            break;
        case "dapi":
            meetingPayload.setDapi(in.nextString());
            break;
        case "acme1":
            meetingPayload.setAcme1(in.nextString());
            break;
        case "acme2":
            meetingPayload.setAcme2(in.nextLong());
            break;
        case "acme3":
            meetingPayload.setAcme3(in.nextLong());
            break;
        case "acme4":
            NginxClojureRT.log.info(TAG + "TypeAdapter Reader is reading acme4...");
            meetingPayload.setAcme4(in.nextLong());
            break;
        case "acme5":
            meetingPayload.setAcme5(in.nextLong());
            break;
        case "acme6":
            meetingPayload.setAcme6(in.nextLong());
            break;
        case "acme7":
            ArrayList<String> attendees = new ArrayList<>();
            in.beginArray();
            while (in.hasNext()) {
                attendees.add(in.nextString());
            }
            in.endArray();
            meetingPayload.setAcme7(attendees);
            break;
        case "acme8":
            meetingPayload.setAcme8(in.nextString());
            break;
        }
    }
    in.endObject();

    return meetingPayload;
}

From source file:com.cardinity.json.UtcDateTypeAdapter.java

License:Apache License

@Override
public Date read(JsonReader in) throws IOException {
    try {/*from ww  w.  ja  va 2s .c  o  m*/
        switch (in.peek()) {
        case NULL:
            in.nextNull();
            return null;
        default:
            String date = in.nextString();
            // Instead of using iso8601Format.parse(value), we use Jackson's date parsing
            // This is because Android doesn't support XXX because it is JDK 1.6
            return parse(date, new ParsePosition(0));
        }
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

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  www  . jav  a2 s  .  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.confighub.core.utils.Utils.java

License:Open Source License

private static boolean isJsonValid(final JsonReader jsonReader) throws IOException {
    try {//  ww w.  java2s  .c o m
        JsonToken token;
        while ((token = jsonReader.peek()) != END_DOCUMENT && token != null) {
            skipToken(jsonReader);
        }
        return true;
    } catch (final MalformedJsonException ignored) {
        return false;
    }
}

From source file:com.confighub.core.utils.Utils.java

License:Open Source License

private static void skipToken(final JsonReader reader) throws IOException {
    final JsonToken token = reader.peek();
    switch (token) {
    case BEGIN_ARRAY:
        reader.beginArray();/*from   ww  w  . j a v  a2 s .  com*/
        break;
    case END_ARRAY:
        reader.endArray();
        break;
    case BEGIN_OBJECT:
        reader.beginObject();
        break;
    case END_OBJECT:
        reader.endObject();
        break;
    case NAME:
        reader.nextName();
        break;
    case STRING:
    case NUMBER:
    case BOOLEAN:
    case NULL:
        reader.skipValue();
        break;
    case END_DOCUMENT:
    default:
        throw new AssertionError(token);
    }
}

From source file:com.continuuity.loom.codec.json.LowercaseEnumTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }/*from www .  ja  v a 2s .c o  m*/

    final Map<String, T> lowercaseToConstant = Maps.newHashMap();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                String next = reader.nextString();
                return lowercaseToConstant.get(next);
            }
        }
    };
}