com.google.gson.stream.JsonToken Java Examples

The following examples show how to use com.google.gson.stream.JsonToken. 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: StateTypeAdapter.java    From smarthome with 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 #2
Source File: TypeAdapter.java    From letv with 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 #3
Source File: SystemSettingsJsonAdapter.java    From esjc with 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 #4
Source File: DcatParser.java    From geoportal-server-harvester with 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 #5
Source File: JsonFeedDeserializer.java    From olingo-odata2 with 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 #6
Source File: SafeJsonReader.java    From cukes with 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 #7
Source File: P.java    From MiBandDecompiled with 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 #8
Source File: Gson.java    From framework with 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 #9
Source File: ArrayTypeAdapter.java    From gson with 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 #10
Source File: JsonFeedDeserializer.java    From olingo-odata2 with 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 #11
Source File: DcatParser.java    From geoportal-server-harvester with 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 #12
Source File: Util.java    From kubernetes-elastic-agents with 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 File: R.java    From MiBandDecompiled with 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 #14
Source File: JsonParser.java    From cukes with 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 #15
Source File: PriceLevelAdapter.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: JsonLinkConsumer.java    From cloud-odata-java with 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 #17
Source File: ByteArrayTypeAdapter.java    From sumk with 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 #18
Source File: NumberGsonAdaptable.java    From lastaflute with 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 #19
Source File: BaseCoordinatesTypeAdapter.java    From mapbox-java with 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 #20
Source File: IntOrString.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public IntOrString read(JsonReader jsonReader) throws IOException {
    final JsonToken nextToken = jsonReader.peek();
    if (nextToken == JsonToken.NUMBER) {
        return new IntOrString(jsonReader.nextInt());
    } else if (nextToken == JsonToken.STRING) {
        return new IntOrString(jsonReader.nextString());
    } else {
        throw new IllegalStateException("Could not deserialize to IntOrString. Was " + nextToken);
    }
}
 
Example #21
Source File: TypeAdapters.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override
public Locale read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  String locale = in.nextString();
  StringTokenizer tokenizer = new StringTokenizer(locale, "_");
  String language = null;
  String country = null;
  String variant = null;
  if (tokenizer.hasMoreElements()) {
    language = tokenizer.nextToken();
  }
  if (tokenizer.hasMoreElements()) {
    country = tokenizer.nextToken();
  }
  if (tokenizer.hasMoreElements()) {
    variant = tokenizer.nextToken();
  }
  if (country == null && variant == null) {
    return new Locale(language);
  } else if (variant == null) {
    return new Locale(language, country);
  } else {
    return new Locale(language, country, variant);
  }
}
 
Example #22
Source File: Iso8601DateTypeAdapter.java    From cnode-android with MIT License 5 votes vote down vote up
@Override
public Date read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    String json = in.nextString();

    try {
        return DATE_FORMAT.parse(json);
    } catch (ParseException e) {
        throw new JsonSyntaxException(json, e);
    }
}
 
Example #23
Source File: JsonEntryDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param navigationPropertyName
 * @throws IOException
 * @throws EntityProviderException
 * @throws EdmException
 */
private void readNavigationProperty(final String navigationPropertyName) throws IOException, EntityProviderException,
    EdmException {
  NavigationPropertyInfo navigationPropertyInfo = eia.getNavigationPropertyInfo(navigationPropertyName);
  if (navigationPropertyInfo == null) {
    throw new EntityProviderException(EntityProviderException.ILLEGAL_ARGUMENT.addContent(navigationPropertyName));
  }

  JsonToken peek = reader.peek();
  if (peek == JsonToken.BEGIN_OBJECT) {
    reader.beginObject();
    String name = reader.nextName();
    if (FormatJson.DEFERRED.equals(name)) {
      reader.beginObject();
      String uri = reader.nextName();
      if (FormatJson.URI.equals(uri)) {
        String value = reader.nextString(); 
        entryMetadata.putAssociationUri(navigationPropertyInfo.getName(), value);
      } else {
        throw new EntityProviderException(EntityProviderException.ILLEGAL_ARGUMENT.addContent(uri));
      }
      reader.endObject();
    } else {
      handleInlineEntries(navigationPropertyName, name);
    }
    reader.endObject();
  } else if (peek == JsonToken.NULL) {
    reader.nextNull();
  } else {
    handleArray(navigationPropertyName);
  }
 }
 
Example #24
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testArray() throws IOException {
  JsonElement element = JsonParser.parseString("[1, 2, 3]");
  JsonTreeReader reader = new JsonTreeReader(element);
  assertEquals(JsonToken.BEGIN_ARRAY, reader.peek());
  reader.beginArray();
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(1, reader.nextInt());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(2, reader.nextInt());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(3, reader.nextInt());
  assertEquals(JsonToken.END_ARRAY, reader.peek());
  reader.endArray();
  assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
 
Example #25
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public Number read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    try {
        return Byte.valueOf((byte) in.nextInt());
    } catch (Throwable e) {
        throw new JsonSyntaxException(e);
    }
}
 
Example #26
Source File: DateAdapters.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
public SumkDate read(JsonReader in) throws IOException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	String v = in.nextString();
	return SumkDate.of(v);
}
 
Example #27
Source File: JsonErrorDocumentConsumer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private void parseInnerError(final JsonReader reader, final ODataErrorContext errorContext) throws IOException {
  JsonToken token = reader.peek();
  if (token == JsonToken.STRING) {
    // implementation for parse content as provided by JsonErrorDocumentProducer
    String innerError = reader.nextString();
    errorContext.setInnerError(innerError);
  } else if (token == JsonToken.BEGIN_OBJECT) {
    // implementation for OData v2 Section 2.2.8.1.2 JSON Error Response
    // (RFC4627 Section 2.2 -> https://www.ietf.org/rfc/rfc4627.txt))
    // currently partial provided
    errorContext.setInnerError(readJson(reader));
  }
}
 
Example #28
Source File: u.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public StringBuilder a(JsonReader jsonreader)
{
    if (jsonreader.peek() == JsonToken.NULL)
    {
        jsonreader.nextNull();
        return null;
    } else
    {
        return new StringBuilder(jsonreader.nextString());
    }
}
 
Example #29
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public InetAddress read(JsonReader in) throws IOException {
    if (in.peek() != JsonToken.NULL) {
        return InetAddress.getByName(in.nextString());
    }
    in.nextNull();
    return null;
}
 
Example #30
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public Number read(JsonReader in) throws IOException {
    JsonToken jsonToken = in.peek();
    switch (jsonToken) {
        case NUMBER:
            return new LazilyParsedNumber(in.nextString());
        case NULL:
            in.nextNull();
            return null;
        default:
            throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
    }
}