Java Code Examples for com.google.gson.stream.JsonReader#beginObject()

The following examples show how to use com.google.gson.stream.JsonReader#beginObject() . 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: HoverTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
public Hover read(final JsonReader in) throws IOException {
  JsonToken nextToken = in.peek();
  if (nextToken == JsonToken.NULL) {
  	return null;
  }
  
  Hover result = new Hover();
  in.beginObject();
  while (in.hasNext()) {
  	String name = in.nextName();
  	switch (name) {
  	case "contents":
  		result.setContents(readContents(in));
  		break;
  	case "range":
  		result.setRange(readRange(in));
  		break;
  	default:
  		in.skipValue();
  	}
  }
  in.endObject();
  return result;
}
 
Example 2
Source File: BsonReaderStreamingTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Test
public void singleValue() throws IOException {
  BsonDocument document = new BsonDocument();
  document.append("value", new BsonInt32(42));

  JsonReader reader = createReader(document);
  check(reader.peek()).is(JsonToken.BEGIN_OBJECT);
  reader.beginObject();
  check(reader.hasNext());
  check(reader.peek()).is(JsonToken.NAME);
  check(reader.nextName()).is("value");
  check(reader.peek()).is(JsonToken.NUMBER);
  check(reader.nextInt()).is(42);
  check(reader.peek()).is(JsonToken.END_OBJECT);
  reader.endObject();
  check(!reader.hasNext());
}
 
Example 3
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private int returnCheckSumForArrayOfJsonObjects(JsonReader reader) throws IOException {
    int checkSum = 0;
    reader.beginArray();
    while (reader.hasNext()) {
        reader.beginObject();
        while (reader.hasNext()) {
            if (reader.nextName().equals("count")) {
                checkSum += reader.nextInt();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    }
    reader.endArray();
    return checkSum;
}
 
Example 4
Source File: JsonErrorDocumentConsumer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private ODataErrorContext parseJson(final JsonReader reader) throws IOException, EntityProviderException {
  ODataErrorContext errorContext;

  if (reader.hasNext()) {
    reader.beginObject();
    String currentName = reader.nextName();
    if (FormatJson.ERROR.equals(currentName)) {
      errorContext = parseError(reader);
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
          "Invalid object with name '" + currentName + "' found."));
    }
  } else {
    throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
        "No content to parse found."));
  }

  errorContext.setContentType(ContentType.APPLICATION_JSON.toContentTypeString());
  return errorContext;
}
 
Example 5
Source File: BsonReaderStreamingTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void object() throws IOException {
  JsonReader reader = createReader("{}");
  check(reader.peek()).is(JsonToken.BEGIN_OBJECT);
  reader.beginObject();
  check(reader.peek()).is(JsonToken.END_OBJECT);
  check(!reader.hasNext());
  reader.endObject();
  check(!reader.hasNext());
}
 
Example 6
Source File: RectangleTypeAdapter.java    From jadx with Apache License 2.0 5 votes vote down vote up
@Override
public Rectangle read(JsonReader in) throws IOException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	in.beginObject();
	Rectangle rectangle = new Rectangle();
	while (in.hasNext()) {
		String name = in.nextName();
		switch (name) {
			case "x":
				rectangle.x = in.nextInt();
				break;
			case "y":
				rectangle.y = in.nextInt();
				break;
			case "width":
				rectangle.width = in.nextInt();
				break;
			case "height":
				rectangle.height = in.nextInt();
				break;

			default:
				throw new IllegalArgumentException("Unknown field in Rectangle: " + name);
		}
	}
	in.endObject();
	return rectangle;
}
 
Example 7
Source File: ProteusTypeAdapterFactory.java    From proteus with Apache License 2.0 5 votes vote down vote up
public Map<String, Value> readData(JsonReader in) throws IOException {
  JsonToken peek = in.peek();
  if (peek == JsonToken.NULL) {
    in.nextNull();
    return new HashMap<>();
  }

  if (peek != JsonToken.BEGIN_OBJECT) {
    throw new JsonSyntaxException("data must be a Map<String, String>.");
  }

  Map<String, Value> data = new LinkedHashMap<>();

  in.beginObject();
  while (in.hasNext()) {
    JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
    String key = in.nextString();
    Value value = VALUE_TYPE_ADAPTER.read(in);
    Value compiled = AttributeProcessor.staticPreCompile(value, context, PROTEUS_INSTANCE_HOLDER.getProteus().functions);
    if (compiled != null) {
      value = compiled;
    }
    Value replaced = data.put(key, value);
    if (replaced != null) {
      throw new JsonSyntaxException("duplicate key: " + key);
    }
  }
  in.endObject();

  return data;
}
 
Example 8
Source File: TranslationRequestStream.java    From joshua with 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();
  }
}
 
Example 9
Source File: FeatureAdapter.java    From geogson with Apache License 2.0 5 votes vote down vote up
private void readProperties(JsonReader in, Feature.Builder builder) throws IOException {
    if(in.peek() == JsonToken.NULL) {
        in.nextNull();
        builder.withProperties(Collections.emptyMap());
    } else {
        in.beginObject();
        while (in.hasNext()) {
            String name = in.nextName();
            JsonElement value = jsonParser.parse(in);
            builder.withProperty(name, value);
        }
        in.endObject();
    }
}
 
Example 10
Source File: CustomMessageEntry.java    From ForgeHax with MIT License 5 votes vote down vote up
@Override
public void deserialize(JsonReader reader) throws IOException {
  reader.beginObject();
  
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "msg":
        setMessage(reader.nextString());
        break;
    }
  }
  
  reader.endObject();
}
 
Example 11
Source File: FeatureAdapter.java    From geogson with Apache License 2.0 5 votes vote down vote up
@Override
public Feature read(JsonReader in) throws IOException {
    Feature.Builder builder = Feature.builder();
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
    } else if (in.peek() == JsonToken.BEGIN_OBJECT) {
        in.beginObject();

        while (in.hasNext()) {
            String name = in.nextName();
            if (TYPE_NAME.equals(name)) {
                String value = in.nextString();
                if(!value.equalsIgnoreCase(FEATURE_TYPE)) {
                    throw new IllegalArgumentException("The given json is not a valid Feature, the type must be Feature, current type=" + value);
                }
            } else if (PROPERTIES_NAME.equals(name)) {
                readProperties(in, builder);
            } else if (GEOMETRY_NAME.equals(name)) {
                builder.withGeometry(gson.fromJson(in, Geometry.class));
            } else if (ID_NAME.equals(name)) {
                builder.withId(Optional.ofNullable(in.nextString()));
            } else {
                // Skip unknown value.
                in.skipValue();
            }
        }

        in.endObject();

    } else {
        throw new IllegalArgumentException("The given json is not a valid Feature: " + in.peek());
    }

    return builder.build();
}
 
Example 12
Source File: JsonParser.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> parseJsonObject(JsonReader jr) throws IOException {
  jr.beginObject();
  Map<String, Object> obj = new LinkedHashMap<String, Object>();
  while (jr.hasNext()) {
    String name = jr.nextName();
    Object value = parseRecursive(jr);
    obj.put(name, value);
  }
  checkState(jr.peek() == JsonToken.END_OBJECT, "Bad token: " + jr.getPath());
  jr.endObject();
  return Collections.unmodifiableMap(obj);
}
 
Example 13
Source File: Car3TypeAdapter.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
@Override
public Car3 read(JsonReader reader) throws IOException {

    Car3 car = new Car3();
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("mark")) {
            car.setMark(reader.nextString());
        } else if (name.equals("model")) {
            car.setModel(reader.nextInt());
        } else if (name.equals("type")) {
            car.setType(reader.nextString());
        } else if (name.equals("maker")) {
            car.setType(reader.nextString());
        } else if (name.equals("cost")) {
            double cost = reader.nextDouble();
            double costExcludingVAT = cost / 1.21;
            car.setCost(costExcludingVAT);  //Remove VAT 21%
        } else if (name.equals("colors") && reader.peek() != JsonToken.NULL) {
            car.setColors(readStringArray(reader));
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return car;
}
 
Example 14
Source File: JsonPropertyConsumer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
protected void readAndCheckTypeInfo(final JsonReader reader, String expectedTypeName)
        throws IOException, EntityProviderException {
  reader.beginObject();
  if (!FormatJson.TYPE.equals(reader.nextName())) {
    throw new EntityProviderException(EntityProviderException.MISSING_ATTRIBUTE.addContent(FormatJson.TYPE)
        .addContent(FormatJson.METADATA));
  }
  final String actualTypeName = reader.nextString();
  if (!expectedTypeName.equals(actualTypeName)) {
    throw new EntityProviderException(EntityProviderException.INVALID_ENTITYTYPE.addContent(expectedTypeName)
        .addContent(actualTypeName));
  }
  reader.endObject();
}
 
Example 15
Source File: SparseArrayTypeAdapter.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
@Override
public SparseArray<T> read(JsonReader in) throws IOException {
    SparseArray<T> map = new SparseArray<>();
    in.beginObject();
    while (in.hasNext()){
        String name = in.nextName();
        map.put(Integer.parseInt(name), mAdapter.read(in));
    }
    in.endObject();
    return map;
}
 
Example 16
Source File: Car3SparseArrayTypeAdapter.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
@Override
public SparseArray<Car3> read(JsonReader in) throws IOException {
    SparseArray<Car3> map = new SparseArray<>();
    in.beginObject();
    while (in.hasNext()){
        String name = in.nextName();
        map.put(Integer.parseInt(name), mAdapter.read(in));
    }
    in.endObject();
    return map;
}
 
Example 17
Source File: IndexTMDB.java    From quaerite with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("java -jar o.m.q.examples.IndexTMDB tmdb.json " +
                "http://localhost:8983/solr/tmdb");
        System.exit(0);
    }
    Path p = Paths.get(args[0]);
    SearchClient searchClient = SearchClientFactory.getClient(args[1]);
    int cnt = 0;
    long start = System.currentTimeMillis();
    List<Movie> movies = new ArrayList<>();
    String idField = searchClient.getDefaultIdField();
    try (Reader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
        JsonReader jsonReader = new JsonReader(reader);
        jsonReader.beginObject();
        while (jsonReader.hasNext()) {
            Movie movie = nextMovie(jsonReader);
            movies.add(movie);
            cnt++;
            if (movies.size() >= 1000) {
                searchClient.addDocuments(buildDocuments(idField, movies));
                movies.clear();
                System.out.println("indexed " + cnt + " in " +
                        (System.currentTimeMillis() - start) + " ms");
            }
        }
        jsonReader.endObject();
    }
    searchClient.addDocuments(buildDocuments(idField, movies));
    System.out.println("finished indexing " + cnt + " in " +
            (System.currentTimeMillis() - start) + " ms");
}
 
Example 18
Source File: ResponseAdapter.java    From feign with Apache License 2.0 4 votes vote down vote up
/**
 * the wikipedia api doesn't use json arrays, rather a series of nested objects.
 */
@Override
public WikipediaExample.Response<X> read(JsonReader reader) throws IOException {
  WikipediaExample.Response<X> pages = new WikipediaExample.Response<X>();
  reader.beginObject();
  while (reader.hasNext()) {
    String nextName = reader.nextName();
    if ("query".equals(nextName)) {
      reader.beginObject();
      while (reader.hasNext()) {
        if (query().equals(reader.nextName())) {
          reader.beginObject();
          while (reader.hasNext()) {
            // each element is in form: "id" : { object }
            // this advances the pointer to the value and skips the key
            reader.nextName();
            reader.beginObject();
            pages.add(build(reader));
            reader.endObject();
          }
          reader.endObject();
        } else {
          reader.skipValue();
        }
      }
      reader.endObject();
    } else if ("continue".equals(nextName)) {
      reader.beginObject();
      while (reader.hasNext()) {
        if ("gsroffset".equals(reader.nextName())) {
          pages.nextOffset = reader.nextLong();
        } else {
          reader.skipValue();
        }
      }
      reader.endObject();
    } else {
      reader.skipValue();
    }
  }
  reader.endObject();
  return pages;
}
 
Example 19
Source File: MessageJsonSerializer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public Message read(JsonReader in) throws IOException {
    in.beginObject();
    Message.Kind kind = Message.Kind.UNKNOWN;
    String text = "";
    String rawMessage = null;
    Optional<String> toolName = Optional.absent();
    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(TOOL_NAME)) {
            toolName = Optional.of(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, toolName, sourceFilePositions);
    } else {
        return new Message(kind, text, rawMessage, toolName, ImmutableList.of(SourceFilePosition.UNKNOWN));
    }
}
 
Example 20
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testFacetTrueButNull() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("facet", "true");
    runner.setProperty("stats", "true");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();

    runner.assertTransferCount(QuerySolr.RESULTS, 1);
    runner.assertTransferCount(QuerySolr.FACETS, 1);
    runner.assertTransferCount(QuerySolr.STATS, 1);

    // Check for empty nestet Objects in JSON
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.FACETS).get(0)))));
    reader.beginObject();
    while (reader.hasNext()) {
        if (reader.nextName().equals("facet_queries")) {
            reader.beginArray();
            assertFalse(reader.hasNext());
            reader.endArray();
        } else {
            reader.beginObject();
            assertFalse(reader.hasNext());
            reader.endObject();
        }
    }
    reader.endObject();

    JsonReader reader_stats = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0)))));
    reader_stats.beginObject();
    assertEquals(reader_stats.nextName(), "stats_fields");
    reader_stats.beginObject();
    assertFalse(reader_stats.hasNext());
    reader_stats.endObject();
    reader_stats.endObject();

    reader.close();
    reader_stats.close();
    solrClient.close();
}