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

The following examples show how to use com.google.gson.stream.JsonToken. 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: mapbox-java   Source File: BaseCoordinatesTypeAdapter.java    License: MIT License 6 votes vote down vote up
protected List<Double> readPointList(JsonReader in) throws IOException {

    if (in.peek() == JsonToken.NULL) {
      throw new NullPointerException();
    }

    List<Double> coordinates = new ArrayList<Double>();
    in.beginArray();
    while (in.hasNext()) {
      coordinates.add(in.nextDouble());
    }
    in.endArray();

    if (coordinates.size() > 2) {
      return CoordinateShifterManager.getCoordinateShifter()
              .shiftLonLatAlt(coordinates.get(0), coordinates.get(1), coordinates.get(2));
    }
    return CoordinateShifterManager.getCoordinateShifter()
            .shiftLonLat(coordinates.get(0), coordinates.get(1));
  }
 
Example 2
Source Project: geoportal-server-harvester   Source File: DcatParser.java    License: Apache License 2.0 6 votes vote down vote up
private void parseContactPoint(JsonRecord record) throws DcatParseException, IOException {
  while (jsonReader.hasNext()) {
    JsonToken token = jsonReader.peek();
    switch (token) {
      case NAME:
        String attrName = jsonReader.nextName();
        if ("fn".equals(attrName)) {
          storeAttribute("contactPoint", record);
        } else if ("hasEmail".equals(attrName)) {
          storeAttribute("mbox", record);
        } else {
          jsonReader.skipValue();
        }
        break;
      case END_OBJECT:
        return;
      default:
        throw new DcatParseException("Unexpected token in the data: " + token);
    }
  }
}
 
Example 3
Source Project: letv   Source File: TypeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
public final TypeAdapter<T> nullSafe() {
    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                TypeAdapter.this.write(out, value);
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() != JsonToken.NULL) {
                return TypeAdapter.this.read(reader);
            }
            reader.nextNull();
            return null;
        }
    };
}
 
Example 4
Source Project: cukes   Source File: SafeJsonReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<JsonToken> iterator() {
    return new Iterator<JsonToken>() {

        @Override
        public boolean hasNext() {
            JsonToken token = peek();
            return token != JsonToken.END_DOCUMENT;
        }

        @Override
        public JsonToken next() {
            getPath();
            return peek();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example 5
Source Project: MiBandDecompiled   Source File: R.java    License: Apache License 2.0 6 votes vote down vote up
public Number a(JsonReader jsonreader)
{
    if (jsonreader.peek() == JsonToken.NULL)
    {
        jsonreader.nextNull();
        return null;
    }
    Integer integer;
    try
    {
        integer = Integer.valueOf(jsonreader.nextInt());
    }
    catch (NumberFormatException numberformatexception)
    {
        throw new JsonSyntaxException(numberformatexception);
    }
    return integer;
}
 
Example 6
Source Project: cukes   Source File: JsonParser.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, String> parsePathToValueMap(String json) {
    Map<String, String> result = new HashMap<String, String>();
    SafeJsonReader reader = new SafeJsonReader(json);
    for (JsonToken token : reader) {
             if (BEGIN_ARRAY == token)  reader.beginArray();
        else if (END_ARRAY == token)    reader.endArray();
        else if (BEGIN_OBJECT == token) reader.beginObject();
        else if (END_OBJECT == token)   reader.endObject();
        else if (NAME == token)         reader.nextName();
        else if (STRING == token)       add(reader.getCurrentPath(), reader.nextString(), result);
        else if (NUMBER == token)       add(reader.getCurrentPath(), reader.nextString(), result);
        else if (BOOLEAN == token)      add(reader.getCurrentPath(), Boolean.toString(reader.nextBoolean()), result);
        else if (NULL == token)         reader.nextNull();
    }
    reader.close();
    return result;
}
 
Example 7
@Override
public PriceLevel read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  if (reader.peek() == JsonToken.NUMBER) {
    int priceLevel = reader.nextInt();

    switch (priceLevel) {
      case 0:
        return PriceLevel.FREE;
      case 1:
        return PriceLevel.INEXPENSIVE;
      case 2:
        return PriceLevel.MODERATE;
      case 3:
        return PriceLevel.EXPENSIVE;
      case 4:
        return PriceLevel.VERY_EXPENSIVE;
    }
  }

  return PriceLevel.UNKNOWN;
}
 
Example 8
Source Project: sumk   Source File: ByteArrayTypeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] rawRead(JsonReader in) throws IOException {
	@SuppressWarnings("resource")
	UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream(128);
	in.beginArray();
	try {
		while (in.hasNext()) {
			if (in.peek() == JsonToken.NULL) {
				in.nextNull();
				continue;
			}
			out.write(in.nextInt());
		}
	} catch (NumberFormatException e) {
		throw new JsonSyntaxException(e);
	}
	in.endArray();
	out.flush();
	return out.toByteArray();
}
 
Example 9
Source Project: smarthome   Source File: StateTypeAdapter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public State read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }
    String value = reader.nextString();
    String[] parts = value.split(TYPE_SEPARATOR);
    String valueTypeName = parts[0];
    String valueAsString = parts[1];

    try {
        @SuppressWarnings("unchecked")
        Class<? extends State> valueType = (Class<? extends State>) Class.forName(valueTypeName);
        List<Class<? extends State>> types = Collections.singletonList(valueType);
        return TypeParser.parseState(types, valueAsString);
    } catch (Exception e) {
        logger.warn("Couldn't deserialize state '{}': {}", value, e.getMessage());
    }
    return null;
}
 
Example 10
Source Project: lastaflute   Source File: NumberGsonAdaptable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public NUM read(JsonReader in) throws IOException { // not use real adapter for options
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    final String str = filterReading(in.nextString());
    if (str == null) { // filter makes it null
        return null;
    }
    if (isEmptyToNullReading() && "".equals(str)) {
        return null;
    }
    try {
        if (str != null && str.trim().isEmpty()) { // e.g. "" or " "
            // toNumber() treats empty as null so throw to keep Gson behavior 
            throw new NumberFormatException("because of empty string: [" + str + "]");
        }
        @SuppressWarnings("unchecked")
        final NUM num = (NUM) DfTypeUtil.toNumber(str, getNumberType());
        return num;
    } catch (RuntimeException e) {
        throwJsonPropertyNumberParseFailureException(in, e);
        return null; // unreachable
    }
}
 
Example 11
Source Project: cloud-odata-java   Source File: JsonLinkConsumer.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> readLinksArray(final JsonReader reader) throws IOException, EntityProviderException {
  List<String> links = new ArrayList<String>();

  reader.beginArray();
  while (reader.hasNext()) {
    reader.beginObject();
    String nextName = reader.nextName();
    if (FormatJson.URI.equals(nextName) && reader.peek() == JsonToken.STRING) {
      links.add(reader.nextString());
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.URI).addContent(nextName));
    }
    reader.endObject();
  }
  reader.endArray();

  return links;
}
 
Example 12
Source Project: kubernetes-elastic-agents   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Number read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    try {
        String result = in.nextString();
        if ("".equals(result)) {
            return null;
        }
        return Integer.parseInt(result);
    } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
    }
}
 
Example 13
Source Project: geoportal-server-harvester   Source File: DcatParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses DCAT using internal listener.
 *
 * @param listener internal listener
 * @throws DcatParseException if parsing DCAT fails
 */
void parse(final ListenerInternal listener) throws DcatParseException, IOException {
  if (!jsonReader.hasNext()) {
    throw new DcatParseException("No more data available.");
  }

  JsonToken token = jsonReader.peek();
  switch (token) {
    case BEGIN_OBJECT:
      version = DcatVersion.DV11;
      jsonReader.beginObject();
      parseContent(listener);
      break;
    case BEGIN_ARRAY:
      jsonReader.beginArray();
      parseRecords(listener);
      break;
    default:
      throw new DcatParseException("Neither array nor object is found.");
  }
}
 
Example 14
Source Project: olingo-odata2   Source File: JsonFeedDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @throws IOException
 * @throws EdmException
 * @throws EntityProviderException
 */
private void readFeed() throws IOException, EdmException, EntityProviderException {
  JsonToken peek = reader.peek();
  if (peek == JsonToken.BEGIN_ARRAY) {
    readArrayContent();
  } else {
    reader.beginObject();
    final String nextName = reader.nextName();
    if (FormatJson.D.equals(nextName)) {
      if (reader.peek() == JsonToken.BEGIN_ARRAY) {
        readArrayContent();
      } else {
        reader.beginObject();
        readFeedContent();
        reader.endObject();
      }
    } else {
      handleName(nextName);
      readFeedContent();
    }

    reader.endObject();
  }
}
 
Example 15
Source Project: gson   Source File: ArrayTypeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override public Object read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  List<E> list = new ArrayList<E>();
  in.beginArray();
  while (in.hasNext()) {
    E instance = componentTypeAdapter.read(in);
    list.add(instance);
  }
  in.endArray();

  int size = list.size();
  Object array = Array.newInstance(componentType, size);
  for (int i = 0; i < size; i++) {
    Array.set(array, i, list.get(i));
  }
  return array;
}
 
Example 16
Source Project: framework   Source File: Gson.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.FLOAT;
  }
  return new TypeAdapter<Number>() {
    @Override public Float read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return (float) in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      float floatValue = value.floatValue();
      checkValidFloatingPoint(floatValue);
      out.value(value);
    }
  };
}
 
Example 17
Source Project: esjc   Source File: SystemSettingsJsonAdapter.java    License: MIT License 6 votes vote down vote up
@Override
public SystemSettings read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        return null;
    }

    SystemSettings.Builder builder = SystemSettings.newBuilder();

    reader.beginObject();

    while (reader.peek() != JsonToken.END_OBJECT && reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case USER_STREAM_ACL:
                builder.userStreamAcl(streamAclJsonAdapter.read(reader));
                break;
            case SYSTEM_STREAM_ACL:
                builder.systemStreamAcl(streamAclJsonAdapter.read(reader));
                break;
        }
    }

    reader.endObject();

    return builder.build();
}
 
Example 18
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 19
Source Project: MiBandDecompiled   Source File: P.java    License: Apache License 2.0 6 votes vote down vote up
public Number a(JsonReader jsonreader)
{
    if (jsonreader.peek() == JsonToken.NULL)
    {
        jsonreader.nextNull();
        return null;
    }
    Byte byte1;
    try
    {
        byte1 = Byte.valueOf((byte)jsonreader.nextInt());
    }
    catch (NumberFormatException numberformatexception)
    {
        throw new JsonSyntaxException(numberformatexception);
    }
    return byte1;
}
 
Example 20
Source Project: letv   Source File: JsonTreeReader.java    License: Apache License 2.0 5 votes vote down vote up
public int nextInt() throws IOException {
    JsonToken token = peek();
    if (token == JsonToken.NUMBER || token == JsonToken.STRING) {
        int result = ((JsonPrimitive) peekStack()).getAsInt();
        popStack();
        return result;
    }
    throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
}
 
Example 21
Source Project: gson   Source File: JsonTreeReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void endObject() throws IOException {
  expect(JsonToken.END_OBJECT);
  popStack(); // empty iterator
  popStack(); // object
  if (stackSize > 0) {
    pathIndices[stackSize - 1]++;
  }
}
 
Example 22
Source Project: letv   Source File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
public StringBuilder read(JsonReader in) throws IOException {
    if (in.peek() != JsonToken.NULL) {
        return new StringBuilder(in.nextString());
    }
    in.nextNull();
    return null;
}
 
Example 23
Source Project: quaerite   Source File: IndexTMDB.java    License: Apache License 2.0 5 votes vote down vote up
private static List<String> extractNamesFromArrayOfObjections(JsonReader jsonReader) throws IOException {
    List<String> names = new ArrayList<>();
    jsonReader.beginArray();
    if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
        jsonReader.endArray();
        return names;
    }
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
        String name = jsonReader.nextName();
        if ("name".equals(name)) {
            String s = jsonReader.nextString();
            if (!StringUtils.isBlank(s)) {
                names.add(s);
            }
        } else {
            jsonReader.skipValue();
        }
        if (jsonReader.peek().equals(JsonToken.END_OBJECT)) {
            jsonReader.endObject();
            if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
                break;
            } else {
                jsonReader.beginObject();
            }
        } else if (jsonReader.peek().equals(JsonToken.BEGIN_OBJECT)) {
            jsonReader.beginObject();
        }
    }
    jsonReader.endArray();
    return names;
}
 
Example 24
@Override
public Number read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  try {
    return in.nextInt();
  } catch (NumberFormatException e) {
    throw new JsonSyntaxException(e);
  }
}
 
Example 25
Source Project: sentry-android   Source File: SentryEnvelopeItemHeaderAdapter.java    License: MIT License 5 votes vote down vote up
@Override
public SentryEnvelopeItemHeader read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  String contentType = null;
  String fileName = null;
  SentryItemType type = SentryItemType.Unknown;
  int length = 0;

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "content_type":
        contentType = reader.nextString();
        break;
      case "filename":
        fileName = reader.nextString();
        break;
      case "type":
        try {
          type = SentryItemType.valueOf(StringUtils.capitalize(reader.nextString()));
        } catch (IllegalArgumentException ignored) {
          // invalid type
        }
        break;
      case "length":
        length = reader.nextInt();
        break;
      default:
        reader.skipValue();
        break;
    }
  }
  reader.endObject();

  return new SentryEnvelopeItemHeader(type, length, contentType, fileName);
}
 
Example 26
Source Project: gson   Source File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UUID read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  return java.util.UUID.fromString(in.nextString());
}
 
Example 27
@Override
public byte[] read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    String base64Encoded = in.nextString();
    return Base64.decode(base64Encoded, Base64.NO_WRAP);
}
 
Example 28
Source Project: immutables   Source File: TypeConversionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void bsonDouble() throws IOException {
  BsonDouble value = new BsonDouble(1.1);
  check(Jsons.readerAt(value).peek()).is(JsonToken.NUMBER);
  check(Jsons.readerAt(value).nextInt()).is(1);
  check(Jsons.readerAt(value).nextLong()).is(1L);
  check(Jsons.readerAt(value).nextDouble()).is(1.1D);
  check(Jsons.readerAt(value).nextString()).is(Double.toString(1.1));
}
 
Example 29
Source Project: olingo-odata2   Source File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static int startJson(final JsonReader reader) throws EntityProviderException {
  // The enclosing "d" and "results" are optional - so we cannot check for the presence
  // but we have to read over them in case they are present.
  JsonToken token;
  try {
    token = reader.peek();
    int openJsonObjects = 0;
    if (JsonToken.BEGIN_OBJECT == token) {
      reader.beginObject();
      openJsonObjects++;
      token = reader.peek();
      if (JsonToken.NAME == token) {
        String name = reader.nextName();
        if (!("d".equals(name) ^ "results".equals(name))) {
          // TODO I18N
          throw new EntityProviderException(EntityProviderException.COMMON, name +
              " not expected, only d or results");
        }
      }

      token = reader.peek();
      if (JsonToken.BEGIN_OBJECT == token) {
        reader.beginObject();
        openJsonObjects++;
      } else if (JsonToken.BEGIN_ARRAY == token) {
        // TODO I18N
        throw new EntityProviderException(EntityProviderException.COMMON, "Array not expected");
      }
    }

    return openJsonObjects;
  } catch (IOException e) {
    // TODO I18N
    throw new EntityProviderException(EntityProviderException.COMMON, e);
  }
}
 
Example 30
@Override
public List<List<Point>> read(JsonReader in) throws IOException {

  if (in.peek() == JsonToken.NULL) {
    throw new NullPointerException();
  }

  if (in.peek() == JsonToken.BEGIN_ARRAY) {

    in.beginArray();
    List<List<Point>> points = new ArrayList<>();

    while (in.peek() == JsonToken.BEGIN_ARRAY) {

      in.beginArray();
      List<Point> listOfPoints = new ArrayList<>();

      while (in.peek() == JsonToken.BEGIN_ARRAY) {
        listOfPoints.add(readPoint(in));
      }
      in.endArray();
      points.add(listOfPoints);
    }
    in.endArray();

    return points;
  }

  throw new GeoJsonException("coordinates should be array of array of array of double");
}