Java Code Examples for com.google.gson.stream.JsonReader

The following examples show how to use com.google.gson.stream.JsonReader. These examples are extracted from open source projects. 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 Project: yangtools   Source File: Bug8083Test.java    License: Eclipse Public License 1.0 7 votes vote down vote up
@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 Project: olingo-odata2   Source File: JsonFeedDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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 Project: grpc-java   Source File: JsonParser.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: SkyblockAddons   Source File: SkyblockAddons.java    License: MIT License 5 votes vote down vote up
@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
@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
@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
@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 Project: morpheus-core   Source File: JsonSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
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 Project: huaweicloud-cs-sdk   Source File: JSON.java    License: Apache License 2.0 5 votes vote down vote up
@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 Project: olingo-odata2   Source File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: citygml4j   Source File: CityJSONInputFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: letv   Source File: TypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
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
/**
 * 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 Project: gson   Source File: TypeAdapterPrecedenceTest.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: openapi-generator   Source File: JSON.java    License: Apache License 2.0 5 votes vote down vote up
@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 Project: softlayer-java   Source File: GsonJsonMarshallerFactory.java    License: MIT License 5 votes vote down vote up
@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
@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 Project: goclipse   Source File: JsonParserX.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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 Project: cloud-odata-java   Source File: JsonPropertyConsumerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 Project: TFC2   Source File: JSONReader.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 Project: gson   Source File: MixedStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: immutables   Source File: Jsons.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 Project: cloud-odata-java   Source File: JsonPropertyConsumerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 Project: EasyHttp   Source File: IntegerTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Number read(JsonReader in) throws IOException {
    Number number = super.read(in);
    if (number != null) {
        return number.intValue();
    }
    return null;
}
 
Example 26
Source Project: cloud-odata-java   Source File: JsonPropertyConsumer.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: proteus   Source File: GsonResponseBodyConverter.java    License: Apache License 2.0 5 votes vote down vote up
@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
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 Project: adventure   Source File: IndexedSerializer.java    License: MIT License 5 votes vote down vote up
@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 Project: joshua   Source File: TranslationRequestStream.java    License: Apache License 2.0 5 votes vote down vote up
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();
  }
}