com.google.gson.stream.JsonReader Java Examples
The following examples show how to use
com.google.gson.stream.JsonReader.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Bug8083Test.java From yangtools with Eclipse Public License 1.0 | 7 votes |
@Test public void testRFC7951InstanceIdentifierPath() throws IOException, URISyntaxException { final String inputJson = loadTextFile("/bug8083/json/foo.json"); // deserialization final NormalizedNodeResult result = new NormalizedNodeResult(); final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result); final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, JSONCodecFactorySupplier.RFC7951.getShared(FULL_SCHEMA_CONTEXT)); jsonParser.parse(new JsonReader(new StringReader(inputJson))); final NormalizedNode<?, ?> transformedInput = result.getResult(); assertTrue(transformedInput instanceof ContainerNode); final ContainerNode container = (ContainerNode) transformedInput; final NormalizedNode<?, ?> child = container.getChild(new NodeIdentifier(FOO_QNAME)).get(); assertTrue(child instanceof LeafNode); assertEquals(TEST_IID, child.getValue()); }
Example #2
Source File: JsonFeedDeserializer.java From olingo-odata2 with Apache License 2.0 | 6 votes |
/** * * @param reader * @param feedMetadata * @throws IOException * @throws EntityProviderException */ protected static void readInlineCount(final JsonReader reader, final FeedMetadataImpl feedMetadata) throws IOException, EntityProviderException { if (reader.peek() == JsonToken.STRING && feedMetadata.getInlineCount() == null) { int inlineCount; try { inlineCount = reader.nextInt(); } catch (final NumberFormatException e) { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(""), e); } if (inlineCount >= 0) { feedMetadata.setInlineCount(inlineCount); } else { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(inlineCount)); } } else { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(reader.peek())); } }
Example #3
Source File: JsonParser.java From grpc-java with Apache License 2.0 | 6 votes |
private static Object parseRecursive(JsonReader jr) throws IOException { checkState(jr.hasNext(), "unexpected end of JSON"); switch (jr.peek()) { case BEGIN_ARRAY: return parseJsonArray(jr); case BEGIN_OBJECT: return parseJsonObject(jr); case STRING: return jr.nextString(); case NUMBER: return jr.nextDouble(); case BOOLEAN: return jr.nextBoolean(); case NULL: return parseJsonNull(jr); default: throw new IllegalStateException("Bad token: " + jr.getPath()); } }
Example #4
Source File: IndexedSerializer.java From adventure with MIT License | 5 votes |
@Override public E read(final JsonReader in) throws IOException { final String string = in.nextString(); final E value = this.map.value(string); if(value != null) { return value; } else { throw new JsonParseException("invalid " + this.name + ": " + string); } }
Example #5
Source File: JsonPropertyConsumerTest.java From cloud-odata-java with Apache License 2.0 | 5 votes |
@Test public void deepComplexPropertyWithStringToStringMappingStandalone() throws Exception { final String complexPropertyJson = "{\"d\":{\"Location\":{\"__metadata\":{\"type\":\"RefScenario.c_Location\"},\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"},\"Country\":\"Germany\"}}}"; JsonReader reader = prepareReader(complexPropertyJson); EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); Map<String, Object> cityMappings = new HashMap<String, Object>(); cityMappings.put("PostalCode", String.class); Map<String, Object> locationMappings = new HashMap<String, Object>(); locationMappings.put("City", cityMappings); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("Location", locationMappings); when(readProperties.getTypeMappings()).thenReturn(mappings); final Map<String, Object> result = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> locationResult = (Map<String, Object>) result.get("Location"); assertEquals(2, locationResult.size()); assertEquals("Germany", locationResult.get("Country")); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) locationResult.get("City"); assertEquals(2, innerResult.size()); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); }
Example #6
Source File: TypeAdapterPrecedenceTest.java From gson with Apache License 2.0 | 5 votes |
private TypeAdapter<Foo> newTypeAdapter(final String name) { return new TypeAdapter<Foo>() { @Override public Foo read(JsonReader in) throws IOException { return new Foo(in.nextString() + " via " + name); } @Override public void write(JsonWriter out, Foo value) throws IOException { out.value(value.name + " via " + name); } }; }
Example #7
Source File: DeviceRegister.java From google-assistant-java-demo with GNU General Public License v3.0 | 5 votes |
/** * Deserialize from json an object in a file * * @param filePath the file in which we stored the object to deserialize * @param targetClass the target class for the deserialization * @param <T> the type of the object to deserialize * @return an optional with the object deserialized if the process succeed */ private <T> Optional<T> readFromFile(String filePath, Class<T> targetClass) { File file = new File(filePath); if (file.exists()) { try { return Optional.of(gson.fromJson(new JsonReader(new FileReader(file)), targetClass)); } catch (IOException e) { LOGGER.warn("Unable to read the content of the file", e); } } return Optional.empty(); }
Example #8
Source File: TypeAdapter.java From letv with Apache License 2.0 | 5 votes |
final T fromJsonTree(JsonElement jsonTree) { try { JsonReader jsonReader = new JsonTreeReader(jsonTree); jsonReader.setLenient(true); return read(jsonReader); } catch (Throwable e) { throw new JsonIOException(e); } }
Example #9
Source File: JSONReader.java From TFC2 with GNU General Public License v3.0 | 5 votes |
public boolean read(File file) { try { Gson gson = new Gson(); InputStream stream; if(file == null) stream = this.getClass().getResourceAsStream(path); else if(file.exists()) { stream = Files.asByteSource(file).openStream(); } else { return false; } InputStreamReader sr = new InputStreamReader(stream); JsonReader reader = new JsonReader(sr); process(reader); reader.close(); } catch(Exception ex) { ex.printStackTrace(); } return true; }
Example #10
Source File: MixedStreamTest.java From gson with Apache License 2.0 | 5 votes |
public void testReaderDoesNotMutateState() throws IOException { Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON)); jsonReader.beginArray(); jsonReader.setLenient(false); gson.fromJson(jsonReader, Car.class); assertFalse(jsonReader.isLenient()); jsonReader.setLenient(true); gson.fromJson(jsonReader, Car.class); assertTrue(jsonReader.isLenient()); }
Example #11
Source File: Jsons.java From immutables with Apache License 2.0 | 5 votes |
/** * Creates reader for position at {@code value} */ static JsonReader readerAt(BsonValue value) throws IOException { BsonDocument doc = new BsonDocument("value", value); BsonReader reader = new BsonReader(new BsonDocumentReader(doc)); // advance AFTER value token reader.beginObject(); check(reader.peek()).is(JsonToken.NAME); check(reader.nextName()).is("value"); return reader; }
Example #12
Source File: JsonPropertyConsumerTest.java From cloud-odata-java with Apache License 2.0 | 5 votes |
@Test(expected = EntityProviderException.class) public void complexPropertyWithInvalidChild() throws Exception { String cityProperty = "{\"d\":{\"City\":{\"Invalid\":\"69124\",\"CityName\":\"Heidelberg\"}}}"; JsonReader reader = prepareReader(cityProperty); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); }
Example #13
Source File: IntegerTypeAdapter.java From EasyHttp with Apache License 2.0 | 5 votes |
@Override public Number read(JsonReader in) throws IOException { Number number = super.read(in); if (number != null) { return number.intValue(); } return null; }
Example #14
Source File: JsonPropertyConsumer.java From cloud-odata-java with Apache License 2.0 | 5 votes |
private Object readSimpleProperty(final JsonReader reader, final EntityPropertyInfo entityPropertyInfo, final Object typeMapping) throws EdmException, EntityProviderException, IOException { final EdmSimpleType type = (EdmSimpleType) entityPropertyInfo.getType(); Object value = null; final JsonToken tokenType = reader.peek(); if (tokenType == JsonToken.NULL) { reader.nextNull(); } else { switch (EdmSimpleTypeKind.valueOf(type.getName())) { case Boolean: if (tokenType == JsonToken.BOOLEAN) { value = reader.nextBoolean(); value = value.toString(); } else { throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName())); } break; case Byte: case SByte: case Int16: case Int32: if (tokenType == JsonToken.NUMBER) { value = reader.nextInt(); value = value.toString(); } else { throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName())); } break; default: if (tokenType == JsonToken.STRING) { value = reader.nextString(); } else { throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName())); } break; } } final Class<?> typeMappingClass = typeMapping == null ? type.getDefaultType() : (Class<?>) typeMapping; return type.valueOfString((String) value, EdmLiteralKind.JSON, entityPropertyInfo.getFacets(), typeMappingClass); }
Example #15
Source File: GsonResponseBodyConverter.java From proteus with Apache License 2.0 | 5 votes |
@Override public T convert(ResponseBody value) throws IOException { TypeAdapter<T> adapter = getAdapter(); JsonReader jsonReader = gson.newJsonReader(value.charStream()); jsonReader.setLenient(true); try { return adapter.read(jsonReader); } finally { value.close(); } }
Example #16
Source File: JsonBookmarkCollection.java From cyberduck with GNU General Public License v3.0 | 5 votes |
protected String readNext(final String name, final JsonReader reader) throws IOException { if(reader.peek() != JsonToken.NULL) { return reader.nextString(); } else { reader.skipValue(); log.warn(String.format("No value for key %s", name)); return null; } }
Example #17
Source File: MCRAltoLinkTypeAdapter.java From mycore with GNU General Public License v3.0 | 5 votes |
@Override public MCRMetsAltoLink read(JsonReader jsonReader) throws IOException { String fileID = null; String begin = null; String end = null; jsonReader.beginObject(); while (jsonReader.hasNext()) { switch (jsonReader.nextName()) { case "altoFile": fileID = jsonReader.nextString(); break; case "begin": begin = jsonReader.nextString(); break; case "end": end = jsonReader.nextString(); break; } } jsonReader.endObject(); if (fileID == null || begin == null || end == null) { throw new MCRException("Cannot read MCRMetsAltoLink! FileID && begin && end expected!"); } return new MCRAltoLinkPlaceHolder(fileID, begin, end); }
Example #18
Source File: TranslationRequestStream.java From joshua with Apache License 2.0 | 5 votes |
public JSONStreamHandler(Reader in) { reader = new JsonReader(in); try { reader.beginObject(); reader.nextName(); // "data" reader.beginObject(); reader.nextName(); // "translations" reader.beginArray(); } catch (IOException e) { e.printStackTrace(); } }
Example #19
Source File: JsonParserStream.java From yangtools with Eclipse Public License 1.0 | 5 votes |
private void readAnyXmlValue(final JsonReader in, final AnyXmlNodeDataWithSchema parent, final String anyXmlObjectName) throws IOException { final String anyXmlObjectNS = getCurrentNamespace().toString(); final Document doc = UntrustedXML.newDocumentBuilder().newDocument(); final Element rootElement = doc.createElementNS(anyXmlObjectNS, anyXmlObjectName); doc.appendChild(rootElement); traverseAnyXmlValue(in, doc, rootElement); final DOMSource domSource = new DOMSource(doc.getDocumentElement()); parent.setValue(domSource); }
Example #20
Source File: KcaDBHelper.java From kcanotify_h5-master with GNU General Public License v3.0 | 5 votes |
public JsonObject getJsonObjectValue(String key) { String value = getValue(key); if (value == null) return null; else { try { JsonReader reader = new JsonReader(new StringReader(value)); reader.setLenient(true); return new Gson().fromJson(reader, JsonObject.class); } catch (Exception e) { return null; } } }
Example #21
Source File: UserRoleAdapter.java From devicehive-java-server with Apache License 2.0 | 5 votes |
@Override public UserRole read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); if (jsonToken == JsonToken.NULL) { in.nextNull(); return null; } else { try { return UserRole.values()[in.nextInt()]; } catch (RuntimeException e) { throw new IOException(Messages.INVALID_USER_ROLE, e); } } }
Example #22
Source File: Excluder.java From framework with GNU Affero General Public License v3.0 | 5 votes |
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class<?> rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter<T>() { /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter<T> delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter<T> delegate() { TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } }; }
Example #23
Source File: Setting.java From ForgeHax with MIT License | 5 votes |
@Override public void deserialize(JsonReader reader) throws IOException { reader.beginObject(); reader.nextName(); // value rawSet(reader.nextString(), true); reader.endObject(); }
Example #24
Source File: DefaultModule.java From proteus with Apache License 2.0 | 5 votes |
@Override public CustomValueTypeAdapter<NestedBinding> create(int type, final ProteusTypeAdapterFactory factory) { return new CustomValueTypeAdapter<NestedBinding>(type) { @Override public void write(JsonWriter out, NestedBinding value) throws IOException { factory.COMPILED_VALUE_TYPE_ADAPTER.write(out, value.getValue()); } @Override public NestedBinding read(JsonReader in) throws IOException { return NestedBinding.valueOf(factory.COMPILED_VALUE_TYPE_ADAPTER.read(in)); } }; }
Example #25
Source File: UserStatusAdapter.java From devicehive-java-server with Apache License 2.0 | 5 votes |
@Override public UserStatus read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); if (jsonToken == JsonToken.NULL) { in.nextNull(); return null; } else { try { return UserStatus.values()[in.nextInt()]; } catch (RuntimeException e) { throw new IOException(Messages.INVALID_USER_STATUS, e); } } }
Example #26
Source File: InstantAdapter.java From google-maps-services-java with Apache License 2.0 | 5 votes |
/** Read a time from the Places API and convert to a {@link Instant} */ @Override public Instant read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } if (reader.peek() == JsonToken.NUMBER) { // Number is the number of seconds since Epoch. return Instant.ofEpochMilli(reader.nextLong() * 1000L); } throw new UnsupportedOperationException("Unsupported format"); }
Example #27
Source File: TypeAdapters.java From gson with Apache License 2.0 | 5 votes |
@Override public BitSet read(JsonReader in) throws IOException { BitSet bitset = new BitSet(); in.beginArray(); int i = 0; JsonToken tokenType = in.peek(); while (tokenType != JsonToken.END_ARRAY) { boolean set; switch (tokenType) { case NUMBER: set = in.nextInt() != 0; break; case BOOLEAN: set = in.nextBoolean(); break; case STRING: String stringValue = in.nextString(); try { set = Integer.parseInt(stringValue) != 0; } catch (NumberFormatException e) { throw new JsonSyntaxException( "Error: Expecting: bitset number value (1, 0), Found: " + stringValue); } break; default: throw new JsonSyntaxException("Invalid bitset value type: " + tokenType); } if (set) { bitset.set(i); } ++i; tokenType = in.peek(); } in.endArray(); return bitset; }
Example #28
Source File: RequiredFieldTypeAdapterFactory.java From plaid-java with MIT License | 5 votes |
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!type.getRawType().isAssignableFrom(RequiredField.class)) { return null; } final TypeAdapter delegateAdapter = gson.getAdapter(TypeToken.get(((ParameterizedType) type.getType()).getActualTypeArguments()[0])); return new TypeAdapter<T>() { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public void write(JsonWriter out, T value) throws IOException { RequiredField requiredField = (RequiredField) value; if (requiredField == null || !requiredField.isPresent()) { boolean oldSerializeNulls = out.getSerializeNulls(); out.setSerializeNulls(true); out.nullValue(); out.setSerializeNulls(oldSerializeNulls); } else { delegateAdapter.write(out, requiredField.get()); } } @Override @SuppressWarnings("unchecked") public T read(JsonReader reader) throws IOException { return (T) RequiredField.of(delegateAdapter.read(reader)); } }; }
Example #29
Source File: Denominator.java From denominator with Apache License 2.0 | 5 votes |
@Override public Map<String, Object> read(JsonReader in) throws IOException { Map<String, Object> map = delegate.read(in); for (Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() instanceof Double) { entry.setValue(Double.class.cast(entry.getValue()).intValue()); } } return map; }
Example #30
Source File: OptionalTypeAdapterFactory.java From salt-netapi-client with MIT License | 5 votes |
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) { return new TypeAdapter<Optional<A>>() { @Override public Optional<A> read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return Optional.empty(); } else { JsonElement json = TypeAdapters.JSON_ELEMENT.read(in); try { A value = innerAdapter.fromJsonTree(json); return Optional.of(value); } catch (JsonSyntaxException e) { /** * Note : This is a workaround and it only exists because salt doesn't differentiate between a * non-existent grain and a grain which exists but has value set to empty String. * * If an object is expected but instead empty string comes in then we return empty Optional. */ if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() && json.getAsString().isEmpty()) { return Optional.empty(); } throw e; } } } @Override public void write(JsonWriter out, Optional<A> optional) throws IOException { innerAdapter.write(out, optional.orElse(null)); } }; }