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: SkyblockAddons.java From SkyblockAddons with MIT License | 5 votes |
@Mod.EventHandler public void postInit(FMLPostInitializationEvent e) { onlineData = new Gson().fromJson(new JsonReader(utils.getBufferedReader("data.json")), OnlineData.class); configValues.loadValues(); persistentValues.loadValues(); setKeyBindingDescriptions(); usingLabymod = utils.isModLoaded("labymod"); usingOofModv1 = utils.isModLoaded("refractionoof", "1.0"); utils.pullOnlineData(); scheduleMagmaBossCheck(); for (Feature feature : Feature.values()) { if (feature.isGuiFeature()) feature.getSettings().add(EnumUtils.FeatureSetting.GUI_SCALE); if (feature.isColorFeature()) feature.getSettings().add(EnumUtils.FeatureSetting.COLOR); } if (configValues.isEnabled(Feature.FANCY_WARP_MENU)) { // Load in these textures so they don't lag the user loading them in later... for (IslandWarpGui.Island island : IslandWarpGui.Island.values()) { Minecraft.getMinecraft().getTextureManager().bindTexture(island.getResourceLocation()); } } Minecraft.getMinecraft().getTextureManager().bindTexture(SkyblockAddonsGui.LOGO); Minecraft.getMinecraft().getTextureManager().bindTexture(SkyblockAddonsGui.LOGO_GLOW); }
Example #5
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 #6
Source File: ScreenCaptureTypeAdapter.java From extentreports-java with Apache License 2.0 | 5 votes |
@Override public Media read(JsonReader reader) throws IOException { ScreenCapture sc = ScreenCapture.builder().build(); reader.beginObject(); String fieldName = null; int cycle = 0; while (reader.hasNext()) { JsonToken token = reader.peek(); if (token.equals(JsonToken.NAME)) { fieldName = reader.nextName(); } if ("string".equalsIgnoreCase(token.name()) && fieldName.equalsIgnoreCase("path")) { token = reader.peek(); sc.setPath(reader.nextString()); } if ("string".equalsIgnoreCase(token.name()) && fieldName.equalsIgnoreCase("resolvedPath")) { token = reader.peek(); sc.setResolvedPath(reader.nextString()); } if ("string".equalsIgnoreCase(token.name()) && fieldName.equalsIgnoreCase("base64")) { token = reader.peek(); sc.setBase64(reader.nextString()); } if (cycle++ > 10) return sc; } reader.endObject(); return sc; }
Example #7
Source File: TreeTypeAdapter.java From framework with GNU Affero General Public License v3.0 | 5 votes |
@Override public T read(JsonReader in) throws IOException { if (deserializer == null) { return delegate().read(in); } JsonElement value = Streams.parse(in); if (value.isJsonNull()) { return null; } return deserializer.deserialize(value, typeToken.getType(), gson.deserializationContext); }
Example #8
Source File: JsonSource.java From morpheus-core with Apache License 2.0 | 5 votes |
/** * Returns a newly created JsonReader * @param is the input stream * @return the JsonReader * @throws IOException if there is an I/O exception */ private JsonReader createReader(InputStream is) throws IOException { final String encoding = options.getCharset().name(); if (is instanceof BufferedInputStream) { return new JsonReader(new InputStreamReader(is, encoding)); } else { return new JsonReader(new InputStreamReader(new BufferedInputStream(is), encoding)); } }
Example #9
Source File: TypeAdapters.java From framework with GNU Affero General Public License v3.0 | 5 votes |
public BitSet read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } 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 #10
Source File: JSON.java From huaweicloud-cs-sdk with Apache License 2.0 | 5 votes |
@Override public LocalDate read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return LocalDate.parse(date, formatter); } }
Example #11
Source File: JsonUtils.java From olingo-odata2 with Apache License 2.0 | 5 votes |
public static boolean endJson(final JsonReader reader, final int openJsonObjects) throws IOException, EntityProviderException { for (int closedJsonObjects = 0; closedJsonObjects < openJsonObjects; closedJsonObjects++) { reader.endObject(); } return reader.peek() == JsonToken.END_DOCUMENT; }
Example #12
Source File: CityJSONInputFactory.java From citygml4j with Apache License 2.0 | 5 votes |
public CityJSONReader createCityJSONReader(File file, String encoding) throws CityJSONReadException { try { return new CityJSONReader(new JsonReader(new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))), this); } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new CityJSONReadException("Caused by: ", e); } }
Example #13
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 #14
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 #15
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 #16
Source File: JSON.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public OffsetDateTime read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); if (date.endsWith("+0000")) { date = date.substring(0, date.length()-5) + "Z"; } return OffsetDateTime.parse(date, formatter); } }
Example #17
Source File: GsonJsonMarshallerFactory.java From softlayer-java with MIT License | 5 votes |
@Override public GregorianCalendar read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String date = in.nextString(); // Remove the colon date = date.substring(0, date.length() - 3) + date.substring(date.length() - 2); // Use decimal presence to determine format and trim to ms precision DateFormat format; int decimalIndex = date.indexOf('.'); if (decimalIndex != -1) { date = trimToMillisecondPrecision(date, decimalIndex); format = subSecondFormat.get(); } else { format = secondFormat.get(); } GregorianCalendar calendar = new GregorianCalendar(); try { calendar.setTime(format.parse(date)); } catch (ParseException e) { throw new RuntimeException(e); } return calendar; }
Example #18
Source File: TypeAdapters.java From framework with GNU Affero General Public License v3.0 | 5 votes |
@Override public Number read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } try { return (short) in.nextInt(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } }
Example #19
Source File: JsonParserX.java From goclipse with Eclipse Public License 1.0 | 5 votes |
public static boolean isEndOfInput(JsonReader jsonReader) throws IOException { try { return jsonReader.peek() == JsonToken.END_DOCUMENT; } catch(IOException e) { // Why the hell GSON doesn't have a proper way to check for empty document? // Need to review on future versions if(e.getMessage().startsWith("End of input")) { return true; } throw e; } }
Example #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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(); } }