List of usage examples for com.google.gson.stream JsonToken STRING
JsonToken STRING
To view the source code for com.google.gson.stream JsonToken STRING.
Click Source Link
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 av a2 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.gilecode.yagson.adapters.TypeAdvisableComplexTypeAdapter.java
License:Apache License
public T read(JsonReader in, ReadContext ctx) throws IOException { JsonToken nextToken = in.peek();//from www. j av a 2 s . com if (nextToken == JsonToken.NULL) { in.nextNull(); return null; } else if (nextToken == JsonToken.STRING) { // for complex type adapters, each string is a reference, no isReferenceString() match required String reference = in.nextString(); T referenced = ctx.refsContext().getReferencedObject(reference); return referenced; } return readOptionallyAdvisedInstance(in, ctx); }
From source file:com.github.gv2011.hprops.Converter.java
License:Open Source License
private void dispatch(final JsonReader json, final Consumer<Property> target, final JsonToken t, final String key) { if (t.equals(JsonToken.BOOLEAN)) write(target, key, getBoolean(json)); else if (t.equals(JsonToken.STRING)) write(target, key, getString(json)); else if (t.equals(JsonToken.NUMBER)) write(target, key, getNumber(json)); else if (t.equals(JsonToken.BEGIN_OBJECT)) doObject(json, target, key);/*w w w . java 2s. c o m*/ else if (t.equals(JsonToken.BEGIN_ARRAY)) doList(json, target, key); else if (t.equals(JsonToken.NULL)) getNull(json); else throw new IllegalArgumentException(t.toString()); }
From source file:com.goide.dlv.JsonReaderEx.java
License:Apache License
/** * Returns the type of the next token without consuming it. *///from ww w . j a va 2 s . c om @NotNull public JsonToken peek() { 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.google.gerrit.httpd.restapi.RestApiServlet.java
License:Apache License
private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException { if (isType(JSON_TYPE, req.getContentType())) { try (BufferedReader br = req.getReader(); JsonReader json = new JsonReader(br)) { json.setLenient(true);/* w w w . ja v a2s . c o m*/ JsonToken first; try { first = json.peek(); } catch (EOFException e) { throw new BadRequestException("Expected JSON object"); } if (first == JsonToken.STRING) { return parseString(json.nextString(), type); } return OutputFormat.JSON.newGson().fromJson(json, type); } } else if (("PUT".equals(req.getMethod()) || "POST".equals(req.getMethod())) && acceptsRawInput(type)) { return parseRawInput(req, type); } else if ("DELETE".equals(req.getMethod()) && hasNoBody(req)) { return null; } else if (hasNoBody(req)) { return createInstance(type); } else if (isType("text/plain", req.getContentType())) { try (BufferedReader br = req.getReader()) { char[] tmp = new char[256]; StringBuilder sb = new StringBuilder(); int n; while (0 < (n = br.read(tmp))) { sb.append(tmp, 0, n); } return parseString(sb.toString(), type); } } else if ("POST".equals(req.getMethod()) && isType(FORM_TYPE, req.getContentType())) { return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type); } else { throw new BadRequestException("Expected Content-Type: " + JSON_TYPE); } }
From source file:com.google.maps.internal.LocalTimeAdapter.java
License:Open Source License
/** * Read a time from the Places API and convert to a {@link LocalTime} */// w w w . ja v a2 s . c o m @Override public LocalTime read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } if (reader.peek() == JsonToken.STRING) { DateTimeFormatter dtf = DateTimeFormat.forPattern("HHmm"); return LocalTime.parse(reader.nextString(), dtf); } throw new UnsupportedOperationException("Unsupported format"); }
From source file:com.gs.reladomo.serial.gson.GsonWrappedListTypedAdapter.java
License:Apache License
@Override public SerializedList<U, T> read(JsonReader jsonReader) throws IOException { ReladomoDeserializer deserializer;//from w ww. j av a2 s. com if (this.typeClass == null) { deserializer = new ReladomoDeserializer(); } else { deserializer = new ReladomoDeserializer(typeClass); } deserializer.setIgnoreUnknown(); JsonDeserializerState state = JsonDeserializerState.ListStartState.INSTANCE; while (true) { JsonToken nextToken = jsonReader.peek(); //BEGIN_ARRAY, END_ARRAY, BEGIN_OBJECT, END_OBJECT, NAME, STRING, NUMBER, BOOLEAN, NULL, END_DOCUMENT; if (JsonToken.BEGIN_OBJECT == nextToken) { jsonReader.beginObject(); state = state.startObject(deserializer); } else if (JsonToken.END_OBJECT == nextToken) { jsonReader.endObject(); state = state.endObject(deserializer); } else if (JsonToken.BEGIN_ARRAY == nextToken) { jsonReader.beginArray(); state = state.startArray(deserializer); } else if (JsonToken.END_ARRAY == nextToken) { jsonReader.endArray(); state = state.endArray(deserializer); } else if (JsonToken.BOOLEAN == nextToken) { if (jsonReader.nextBoolean()) { state = state.valueTrue(deserializer); } else { state = state.valueFalse(deserializer); } } else if (JsonToken.NAME == nextToken) { String name = jsonReader.nextName(); state = state.fieldName(name, deserializer); } else if (JsonToken.NUMBER == nextToken) { String value = jsonReader.nextString(); state = state.valueString(value, deserializer); // we do the parsing to avoid precision loss } else if (JsonToken.STRING == nextToken) { String value = jsonReader.nextString(); Attribute attribute = deserializer.getCurrentAttribute(); if (attribute instanceof TimestampAttribute) { Timestamp timestamp = GsonReladomoTypeAdapterSerialWriter.jsonToTimestamp(value); state = state.valueTimestamp(timestamp, deserializer); } else { state = state.valueString(value, deserializer); } } else if (JsonToken.NULL == nextToken) { jsonReader.nextNull(); state = state.valueNull(deserializer); } else if (JsonToken.END_DOCUMENT == nextToken) { break; } } return deserializer.getDeserializedResultAsList(); }
From source file:com.gs.reladomo.serial.gson.GsonWrappedTypedAdapter.java
License:Apache License
@Override public Serialized<T> read(JsonReader jsonReader) throws IOException { ReladomoDeserializer deserializer;//from w w w.ja v a 2 s .c o m if (this.typeClass == null) { deserializer = new ReladomoDeserializer(); } else { deserializer = new ReladomoDeserializer(typeClass); } deserializer.setIgnoreUnknown(); JsonDeserializerState state = JsonDeserializerState.NormalParserState.INSTANCE; while (true) { JsonToken nextToken = jsonReader.peek(); //BEGIN_ARRAY, END_ARRAY, BEGIN_OBJECT, END_OBJECT, NAME, STRING, NUMBER, BOOLEAN, NULL, END_DOCUMENT; if (JsonToken.BEGIN_OBJECT == nextToken) { jsonReader.beginObject(); state = state.startObject(deserializer); } else if (JsonToken.END_OBJECT == nextToken) { jsonReader.endObject(); state = state.endObject(deserializer); } else if (JsonToken.BEGIN_ARRAY == nextToken) { jsonReader.beginArray(); state = state.startArray(deserializer); } else if (JsonToken.END_ARRAY == nextToken) { jsonReader.endArray(); state = state.endArray(deserializer); } else if (JsonToken.BOOLEAN == nextToken) { if (jsonReader.nextBoolean()) { state = state.valueTrue(deserializer); } else { state = state.valueFalse(deserializer); } } else if (JsonToken.NAME == nextToken) { String name = jsonReader.nextName(); state = state.fieldName(name, deserializer); } else if (JsonToken.NUMBER == nextToken) { String value = jsonReader.nextString(); state = state.valueString(value, deserializer); // we do the parsing to avoid precision loss } else if (JsonToken.STRING == nextToken) { String value = jsonReader.nextString(); Attribute attribute = deserializer.getCurrentAttribute(); if (attribute instanceof TimestampAttribute) { Timestamp timestamp = GsonReladomoTypeAdapterSerialWriter.jsonToTimestamp(value); state = state.valueTimestamp(timestamp, deserializer); } else { state = state.valueString(value, deserializer); } } else if (JsonToken.NULL == nextToken) { jsonReader.nextNull(); state = state.valueNull(deserializer); } else if (JsonToken.END_DOCUMENT == nextToken) { break; } } return deserializer.getDeserializedResult(); }
From source file:com.ibm.og.json.type.ContainerConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!ContainerConfig.class.equals(rawType)) { return null; }//w w w .j a v a2s .c om final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override public T read(final JsonReader in) throws IOException { if (JsonToken.STRING == in.peek()) { return (T) new ContainerConfig(in.nextString()); } return delegate.read(in); } }.nullSafe(); }
From source file:com.ibm.watson.developer_cloud.speech_to_text.v1.util.SpeechTimestampTypeAdapter.java
License:Open Source License
@Override public SpeechTimestamp read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull();/*from www.j ava2 s .c om*/ return null; } final SpeechTimestamp speechTimestamp = new SpeechTimestamp(); reader.beginArray(); if (reader.peek() == JsonToken.STRING) { speechTimestamp.setWord(reader.nextString()); } if (reader.peek() == JsonToken.NUMBER) { speechTimestamp.setStartTime(reader.nextDouble()); } if (reader.peek() == JsonToken.NUMBER) { speechTimestamp.setEndTime(reader.nextDouble()); } reader.endArray(); return speechTimestamp; }