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

The following examples show how to use com.google.gson.stream.JsonReader#hasNext() . 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: CategoriesTypeAdapter.java    From greenbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Categories read(JsonReader reader) throws IOException {
	reader.beginObject();
	checkState(NAME_CATEGORIES.equals(reader.nextName()));
	reader.beginArray();

	ImmutableList.Builder<Category> elements = ImmutableList.<Category> builder();
	while (reader.hasNext()) {
		if (reader.peek() == JsonToken.BEGIN_OBJECT) {
			elements.add(gson.getAdapter(Category.class).read(reader));
		} else {
			elements.add(readCategory(reader.nextString()));
		}
	}
	reader.endArray();
	reader.endObject();

	return new Categories(elements.build());
}
 
Example 2
Source File: AutoPlaylistRule.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("WrongConstant")
@Override
public AutoPlaylistRule read(JsonReader in) throws IOException {
    Factory factory = new Factory();

    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
            case "type":
                factory.setType(in.nextInt());
                break;
            case "match":
                factory.setMatch(in.nextInt());
                break;
            case "field":
                factory.setField(in.nextInt());
                break;
            case "value":
                factory.setValue(in.nextString());
        }
    }
    in.endObject();

    return factory.build();
}
 
Example 3
Source File: TypeAdapters.java    From gson with Apache License 2.0 6 votes vote down vote up
@Override public AtomicIntegerArray read(JsonReader in) throws IOException {
    List<Integer> list = new ArrayList<Integer>();
    in.beginArray();
    while (in.hasNext()) {
      try {
        int integer = in.nextInt();
        list.add(integer);
      } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
      }
    }
    in.endArray();
    int length = list.size();
    AtomicIntegerArray array = new AtomicIntegerArray(length);
    for (int i = 0; i < length; ++i) {
      array.set(i, list.get(i));
    }
    return array;
}
 
Example 4
Source File: SBSApiBase.java    From iview-android-tv with MIT License 6 votes vote down vote up
private List<EpisodeModel> readEntriesArray(JsonReader reader) throws IOException {
    reader.beginArray();
    Gson gson = new GsonBuilder().create();
    List<EpisodeModel> all = new ArrayList<>();
    while (reader.hasNext()) {
        try {
            Entry entry = gson.fromJson(reader, Entry.class);
            EpisodeModel ep = EpisodeModel.create(entry);
            all.add(ep);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
    reader.endArray();
    return all;
}
 
Example 5
Source File: TestQuerySolr.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 6
Source File: BaseTypeAdapter.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public T read(JsonReader in) throws IOException {
    //log("BaseTypeAdapter_read");
    in.beginObject();
    final T t = create() ;
    while (in.hasNext()) {
        GsonProperty prop = getProperty(in.nextName());
        //check null and version
        if(prop == null){
            in.skipValue();
        }else {
            TypeHandler.getTypeHandler(prop).read(in, prop, t);
        }
    }
    in.endObject();
    return t;
}
 
Example 7
Source File: AbstractEntityWithIdJsonAdapter.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public AbstractEntityWithId read(JsonReader in) throws IOException{
	String entityType = null;
	String id = null;
	
	in.beginObject();
	while (in.hasNext()) {
		switch (in.nextName()) {
		case ENTITY_TYPE:
			entityType = in.nextString();
			break;
		case ID:
			id = in.nextString();
			break;
		default:
			break;
		}
	}
	in.endObject();
	
	return tryToLoad(entityType, id);
}
 
Example 8
Source File: LaYourCollectionTypeAdapterFactory.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<E> read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    final List<E> mutableList = new ArrayList<E>();
    in.beginArray();
    while (in.hasNext()) {
        E instance = elementTypeAdapter.read(in);
        mutableList.add(instance);
    }
    in.endArray();
    @SuppressWarnings("unchecked")
    final Iterable<E> ite = (Iterable<E>) yourCollectionCreator.apply(mutableList);
    return ite;
}
 
Example 9
Source File: ThemeInfo.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Integer> read(JsonReader in) throws IOException {
    Map<String, Integer> ret = new HashMap<>();
    in.beginObject();
    while (in.hasNext()) {
        String name = in.nextName();
        int value = Color.parseColor(in.nextString());
        ret.put(name, value);
    }
    in.endObject();
    return ret;
}
 
Example 10
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 5 votes vote down vote up
private Thing readObject(JsonReader reader) throws IOException {
  reader.beginObject();
  Multimap<String, ValueType> properties = LinkedListMultimap.create();
  ListMultimap<String, Thing> reverseMap = LinkedListMultimap.create();
  String typeName = null;
  while (reader.hasNext()) {
    String key = reader.nextName();
    if (JsonLdConstants.TYPE.equals(key)) {
      typeName = reader.nextString();
    } else if (JsonLdConstants.CONTEXT.equals(key)) {
      properties.putAll(key, readContext(reader));
    } else if (JsonLdConstants.REVERSE.equals(key)) {
      reverseMap.putAll(readReverse(reader));
    } else {
      properties.putAll(
          key, readInternal(reader, JsonLdConstants.ID.equals(key) /* acceptNull */));
    }
  }
  reader.endObject();
  if (Strings.isNullOrEmpty(typeName)) {
    // Treat any unrecognized types as Thing.
    typeName = THING;
  }
  // Value of @type should be short type name or full type name.
  // Doesn't support relative IRI or compact IRI for now.
  return buildSchemaOrgObject(typeName, properties, reverseMap);
}
 
Example 11
Source File: CollectionsDeserializationBenchmark.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
 * setting object values by reflection. We should strive to reduce the discrepancy between this
 * and {@link #timeCollectionsDefault(int)} .
 */
public void timeCollectionsReflectionStreaming(int reps) throws Exception {
  for (int i=0; i<reps; ++i) {
    StringReader reader = new StringReader(json);
    JsonReader jr = new JsonReader(reader);
    jr.beginArray();
    List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>();
    while(jr.hasNext()) {
      jr.beginObject();
      BagOfPrimitives bag = new BagOfPrimitives();
      while(jr.hasNext()) {
        String name = jr.nextName();
        for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
          if (field.getName().equals(name)) {
            Class<?> fieldType = field.getType();
            if (fieldType.equals(long.class)) {
              field.setLong(bag, jr.nextLong());
            } else if (fieldType.equals(int.class)) {
              field.setInt(bag, jr.nextInt());
            } else if (fieldType.equals(boolean.class)) {
              field.setBoolean(bag, jr.nextBoolean());
            } else if (fieldType.equals(String.class)) {
              field.set(bag, jr.nextString());
            } else {
              throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
            }
          }
        }
      }
      jr.endObject();
      bags.add(bag);
    }
    jr.endArray();
  }
}
 
Example 12
Source File: TagProperty.java    From ForgeHax with MIT License 5 votes vote down vote up
@Override
public void deserialize(JsonReader reader) throws IOException {
  reader.beginArray();
  while (reader.hasNext()) {
    add(reader.nextString());
  }
  reader.endArray();
}
 
Example 13
Source File: ElasticsearchDependenciesJob.java    From zipkin-dependencies with Apache License 2.0 5 votes vote down vote up
/** returns the lower 64 bits of the trace ID */
@Override public String call(Tuple2<String, String> pair) throws IOException {
  JsonReader reader = new JsonReader(new StringReader(pair._2));
  reader.beginObject();
  while (reader.hasNext()) {
    String nextName = reader.nextName();
    if (nextName.equals("traceId")) {
      String traceId = reader.nextString();
      return traceId.length() > 16 ? traceId.substring(traceId.length() - 16) : traceId;
    } else {
      reader.skipValue();
    }
  }
  throw new MalformedJsonException("no traceId in " + pair);
}
 
Example 14
Source File: TransactionsTypeAdapter.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Transactions read(JsonReader reader) throws IOException {
	reader.beginObject();
	checkState(reader.nextName().equals(NAME_TRANSACTIONS));
	reader.beginArray();

	ImmutableList.Builder<Transaction> elements = ImmutableList.builder();
	while (reader.hasNext()) {
		elements.add(readTransaction(reader.nextString()));
	}

	reader.endArray();
	reader.endObject();
	return new Transactions(elements.build());
}
 
Example 15
Source File: WikipediaExample.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
protected Page build(JsonReader reader) throws IOException {
  Page page = new Page();
  while (reader.hasNext()) {
    String key = reader.nextName();
    if (key.equals("pageid")) {
      page.id = reader.nextLong();
    } else if (key.equals("title")) {
      page.title = reader.nextString();
    } else {
      reader.skipValue();
    }
  }
  return page;
}
 
Example 16
Source File: SourceFileJsonTypeAdapter.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public SourceFile read(JsonReader in) throws IOException {
    switch (in.peek()) {
        case BEGIN_OBJECT:
            in.beginObject();
            String filePath = null;
            String description = null;
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals(PATH)) {
                    filePath = in.nextString();
                } else if (DESCRIPTION.equals(name)) {
                    description = in.nextString();
                } else {
                    in.skipValue();
                }
            }
            in.endObject();
            if (!Strings.isNullOrEmpty(filePath)) {
                File file = new File(filePath);
                if (!Strings.isNullOrEmpty(description)) {
                    return new SourceFile(file, description);
                } else {
                    return new SourceFile(file);
                }
            } else {
                if (!Strings.isNullOrEmpty(description)) {
                    return new SourceFile(description);
                } else {
                    return SourceFile.UNKNOWN;
                }
            }
        case STRING:
            String fileName = in.nextString();
            if (Strings.isNullOrEmpty(fileName)) {
                return SourceFile.UNKNOWN;
            }
            return new SourceFile(new File(fileName));
        default:
            return SourceFile.UNKNOWN;
    }

}
 
Example 17
Source File: RackspaceAdapters.java    From denominator with Apache License 2.0 4 votes vote down vote up
@Override
public Job read(JsonReader reader) throws IOException {
  Job job = new Job();

  reader.beginObject();
  while (reader.hasNext()) {
    String key = reader.nextName();
    if (key.equals("jobId")) {
      job.id = reader.nextString();
      // Hunt for an id in the response
      //   * response.*[0].id
    } else if (key.equals("response")) {
      reader.beginObject();
      while (reader.hasNext()) {
        reader.nextName(); // skip name
        reader.beginArray();
        reader.beginObject();
        while (reader.hasNext()) {
          key = reader.nextName();
          if (key.equals("id")) {
            job.resultId = reader.nextString();
          } else {
            reader.skipValue();
          }
        }
        reader.endObject();
        reader.endArray();
      }
      reader.endObject();
    } else if (key.equals("status")) {
      job.status = reader.nextString();
      // There are two places to find a useful error message
      //   * error.failedItems.faults[0].details <- on delete
      //   * error.details <- on create
    } else if (key.equals("error")) {
      reader.beginObject();
      while (reader.hasNext()) {
        key = reader.nextName();
        if (key.equals("failedItems")) {
          reader.beginObject();
          reader.nextName();
          reader.beginArray();
          reader.beginObject();
          while (reader.hasNext()) {
            key = reader.nextName();
            if (key.equals("details")) {
              job.errorDetails = reader.nextString();
            } else {
              reader.skipValue();
            }
          }
          reader.endObject();
          reader.endArray();
          reader.endObject();
        } else if (key.equals("details") && job.errorDetails == null) {
          job.errorDetails = reader.nextString();
        } else {
          reader.skipValue();
        }
      }
      reader.endObject();
    } else {
      reader.skipValue();
    }
  }

  reader.endObject();

  return job;
}
 
Example 18
Source File: RackspaceAdapters.java    From denominator with Apache License 2.0 4 votes vote down vote up
@Override
public ListWithNext<X> read(JsonReader reader) throws IOException {
  ListWithNext<X> records = new ListWithNext<X>();
  reader.beginObject();
  while (reader.hasNext()) {
    String nextName = reader.nextName();
    if (jsonKey().equals(nextName)) {
      reader.beginArray();
      while (reader.hasNext()) {
        reader.beginObject();
        records.add(build(reader));
        reader.endObject();
      }
      reader.endArray();
    } else if ("links".equals(nextName)) {
      reader.beginArray();
      while (reader.hasNext()) {
        String currentRel = null;
        String currentHref = null;
        reader.beginObject();
        while (reader.hasNext()) {
          String key = reader.nextName();
          if ("rel".equals(key)) {
            currentRel = reader.nextString();
          } else if ("href".equals(key)) {
            currentHref = reader.nextString();
          } else {
            reader.skipValue();
          }
        }
        if ("next".equals(currentRel)) {
          if (currentHref != null) {
            records.next = URI.create(currentHref);
          }
        }
        reader.endObject();
      }
      reader.endArray();
    } else {
      reader.skipValue();
    }
  }
  reader.endObject();
  Collections.sort(records, toStringComparator());
  return records;
}
 
Example 19
Source File: GeometryCollection.java    From mapbox-java with MIT License 4 votes vote down vote up
@Override
public GeometryCollection read(JsonReader jsonReader) throws IOException {
  if (jsonReader.peek() == JsonToken.NULL) {
    jsonReader.nextNull();
    return null;
  }
  jsonReader.beginObject();
  String type = null;
  BoundingBox bbox = null;
  List<Geometry> geometries = null;
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    if (jsonReader.peek() == JsonToken.NULL) {
      jsonReader.nextNull();
      continue;
    }
    switch (name) {
      case "type":
        TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
        if (stringTypeAdapter == null) {
          stringTypeAdapter = gson.getAdapter(String.class);
          this.stringTypeAdapter = stringTypeAdapter;
        }
        type = stringTypeAdapter.read(jsonReader);
        break;

      case "bbox":
        TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
        if (boundingBoxTypeAdapter == null) {
          boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
          this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
        }
        bbox = boundingBoxTypeAdapter.read(jsonReader);
        break;

      case "geometries":
        TypeAdapter<List<Geometry>> listGeometryAdapter = this.listGeometryAdapter;
        if (listGeometryAdapter == null) {
          TypeToken typeToken = TypeToken.getParameterized(List.class, Geometry.class);
          listGeometryAdapter =
                  (TypeAdapter<List<Geometry>>) gson.getAdapter(typeToken);
          this.listGeometryAdapter = listGeometryAdapter;
        }
        geometries = listGeometryAdapter.read(jsonReader);
        break;

      default:
        jsonReader.skipValue();

    }
  }
  jsonReader.endObject();
  return new GeometryCollection(type == null ? "GeometryCollection" : type, bbox, geometries);
}
 
Example 20
Source File: StructuredJsonExamplesProvider.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
private void readFeatureIntoNamespace(long exampleNumber, NamespaceBuilder nsBuilder, JsonReader jsonReader) throws IOException {
	jsonReader.beginObject();

	String name = null;
	Float value = null;

	boolean nameRead = false, valueRead = false;

	while (jsonReader.hasNext()) {

		String propertyNameOriginal = jsonReader.nextName();

		String propertyName = propertyNameOriginal.toLowerCase();

		if (propertyName.equals(StructuredJsonPropertyNames.FEATURE_NAME_PROPERTY)) {

			if (nameRead) {

				throw new ExampleFormatException(exampleNumber, "The 'name' property can only appear once in a feature!");
			}

			name = jsonReader.nextString(); //feature name should never be null, so not doing the null check here. if it's null, let the exception
											//be propagated.

			nameRead = true;

		}
		else if (propertyName.equals(StructuredJsonPropertyNames.FEATURE_VALUE_PROPERTY)) {

			if (valueRead) {

				throw new ExampleFormatException(exampleNumber, "The 'value' property can only appear once in a feature!");
			}

			if (jsonReader.peek() == JsonToken.NULL)
				jsonReader.nextNull();
			else
				value = Float.valueOf((float) jsonReader.nextDouble());

			valueRead = true;

		}
		else {

			throw new ExampleFormatException(exampleNumber, "Unknown property: " + propertyNameOriginal + " found while reading feature!");
		}

	}

	jsonReader.endObject();

	if (StringUtils.isBlank(name) == false) //add feature only if the name exists.
		nsBuilder.addFeature(name, value);
}