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

The following examples show how to use com.google.gson.stream.JsonReader#nextNull() . 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: TraceEvent.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static Object parseSingleValueRecursively(JsonReader reader) throws IOException {
  JsonToken nextToken = reader.peek();
  switch (nextToken) {
    case BOOLEAN:
      return reader.nextBoolean();
    case NULL:
      reader.nextNull();
      return null;
    case NUMBER:
      // Json's only numeric type is number, using Double to accommodate all types
      return reader.nextDouble();
    case STRING:
      return reader.nextString();
    case BEGIN_OBJECT:
      return parseMap(reader);
    case BEGIN_ARRAY:
      return parseArray(reader);
    default:
      throw new IOException("Unexpected token " + nextToken.name());
  }
}
 
Example 2
Source File: ArrayTypeAdapter.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
  Object array = Array.newInstance(componentType, list.size());
  for (int i = 0; i < list.size(); i++) {
    Array.set(array, i, list.get(i));
  }
  return array;
}
 
Example 3
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 4
Source File: JSON.java    From huaweicloud-cs-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public java.sql.Date read(JsonReader in) throws IOException {
    switch (in.peek()) {
        case NULL:
            in.nextNull();
            return null;
        default:
            String date = in.nextString();
            try {
                if (dateFormat != null) {
                    return new java.sql.Date(dateFormat.parse(date).getTime());
                }
                return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
    }
}
 
Example 5
Source File: JSON.java    From huaweicloud-cs-sdk with 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 6
Source File: JsonUtil.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
private static Object read2Str(JsonReader in, boolean str) throws IOException {
    JsonToken token = in.peek();
    switch (token) {
    case BEGIN_ARRAY:
        List<Object> list = new LinkedList<Object>();
        in.beginArray();
        while (in.hasNext()) {
            list.add(read2Str(in, false));
        }
        in.endArray();
        return str ? JsonUtil.toJson(list) : list;

    case BEGIN_OBJECT:
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        in.beginObject();
        while (in.hasNext()) {
            map.put(in.nextName(), read2Str(in, false));
        }
        in.endObject();
        return str ? JsonUtil.toJson(map) : map;

    case STRING:
        return in.nextString();

    case NUMBER:
        return in.nextString();
    case BOOLEAN:
        return in.nextBoolean();

    case NULL:
        in.nextNull();
        return "";
    default:
        return in.nextString();
    }
}
 
Example 7
Source File: URITypeAdapter.java    From problem with MIT License 5 votes vote down vote up
@Override
public URI read(final JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return Problem.DEFAULT_TYPE;
    }

    return URI.create(in.nextString());
}
 
Example 8
Source File: JSON.java    From eve-esi with 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 9
Source File: JSON.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] read(JsonReader in) throws IOException {
    switch (in.peek()) {
        case NULL:
            in.nextNull();
            return null;
        default:
            String bytesAsBase64 = in.nextString();
            ByteString byteString = ByteString.decodeBase64(bytesAsBase64);
            return byteString.toByteArray();
    }
}
 
Example 10
Source File: LatLngAdapter.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
/**
 * Reads in a JSON object and try to create a LatLng in one of the following formats.
 *
 * <pre>{
 *   "lat" : -33.8353684,
 *   "lng" : 140.8527069
 * }
 *
 * {
 *   "latitude": -33.865257570508334,
 *   "longitude": 151.19287000481452
 * }</pre>
 */
@Override
public LatLng read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  double lat = 0;
  double lng = 0;
  boolean hasLat = false;
  boolean hasLng = false;

  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    if ("lat".equals(name) || "latitude".equals(name)) {
      lat = reader.nextDouble();
      hasLat = true;
    } else if ("lng".equals(name) || "longitude".equals(name)) {
      lng = reader.nextDouble();
      hasLng = true;
    }
  }
  reader.endObject();

  if (hasLat && hasLng) {
    return new LatLng(lat, lng);
  } else {
    return null;
  }
}
 
Example 11
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 5 votes vote down vote up
private List<SchemaOrgType> readInternal(JsonReader reader, boolean acceptNull)
    throws IOException {
  List<SchemaOrgType> list = new ArrayList<>();
  switch (reader.peek()) {
    case STRING:
      list.add(Text.of(reader.nextString()));
      break;
    case NUMBER:
      list.add(Number.of(reader.nextString()));
      break;
    case BOOLEAN:
      if (reader.nextBoolean()) {
        list.add(BooleanEnum.TRUE);
      } else {
        list.add(BooleanEnum.FALSE);
      }
      break;
    case NULL:
      if (acceptNull) {
        reader.nextNull();
        list.add(null);
      } else {
        throw new JsonLdSyntaxException("Found null value for schema.org property value");
      }
      break;
    case BEGIN_OBJECT:
      list.add(readObject(reader));
      break;
    case BEGIN_ARRAY:
      list.addAll(readArray(reader));
      break;
    case END_DOCUMENT:
      throw new JsonLdSyntaxException("Meet end of document");
    case END_OBJECT:
    case END_ARRAY:
    case NAME:
      break;
  }
  return list;
}
 
Example 12
Source File: CollectionGsonAdaptable.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<?> read(JsonReader in) throws IOException {
    if (gsonOption.isListNullToEmptyReading()) {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return Collections.emptyList();
        }
    }
    return embedded.read(in);
}
 
Example 13
Source File: TypeAdapters.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override
public Number read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  return (float) in.nextDouble();
}
 
Example 14
Source File: MapTypeAdapterFactory.java    From letv with Apache License 2.0 5 votes vote down vote up
public Map<K, V> read(JsonReader in) throws IOException {
    JsonToken peek = in.peek();
    if (peek == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    Map<K, V> map = (Map) this.constructor.construct();
    K key;
    if (peek == JsonToken.BEGIN_ARRAY) {
        in.beginArray();
        while (in.hasNext()) {
            in.beginArray();
            key = this.keyTypeAdapter.read(in);
            if (map.put(key, this.valueTypeAdapter.read(in)) != null) {
                throw new JsonSyntaxException("duplicate key: " + key);
            }
            in.endArray();
        }
        in.endArray();
        return map;
    }
    in.beginObject();
    while (in.hasNext()) {
        JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
        key = this.keyTypeAdapter.read(in);
        if (map.put(key, this.valueTypeAdapter.read(in)) != null) {
            throw new JsonSyntaxException("duplicate key: " + key);
        }
    }
    in.endObject();
    return map;
}
 
Example 15
Source File: ZonedDateTimeAdapter.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
/**
 * Read a Time object from a Directions API result and convert it to a {@link ZonedDateTime}.
 *
 * <p>We are expecting to receive something akin to the following:
 *
 * <pre>
 * {
 *   "text" : "4:27pm",
 *   "time_zone" : "Australia/Sydney",
 *   "value" : 1406528829
 * }
 * </pre>
 */
@Override
public ZonedDateTime read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  String timeZoneId = "";
  long secondsSinceEpoch = 0L;

  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    if (name.equals("text")) {
      // Ignore the human-readable rendering.
      reader.nextString();
    } else if (name.equals("time_zone")) {
      timeZoneId = reader.nextString();
    } else if (name.equals("value")) {
      secondsSinceEpoch = reader.nextLong();
    }
  }
  reader.endObject();

  return ZonedDateTime.ofInstant(
      Instant.ofEpochMilli(secondsSinceEpoch * 1000), ZoneId.of(timeZoneId));
}
 
Example 16
Source File: v.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public StringBuffer a(JsonReader jsonreader)
{
    if (jsonreader.peek() == JsonToken.NULL)
    {
        jsonreader.nextNull();
        return null;
    } else
    {
        return new StringBuffer(jsonreader.nextString());
    }
}
 
Example 17
Source File: f.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public Map a(JsonReader jsonreader)
{
    JsonToken jsontoken = jsonreader.peek();
    if (jsontoken == JsonToken.NULL)
    {
        jsonreader.nextNull();
        return null;
    }
    Map map = (Map)d.construct();
    if (jsontoken == JsonToken.BEGIN_ARRAY)
    {
        jsonreader.beginArray();
        for (; jsonreader.hasNext(); jsonreader.endArray())
        {
            jsonreader.beginArray();
            Object obj1 = b.read(jsonreader);
            if (map.put(obj1, c.read(jsonreader)) != null)
            {
                throw new JsonSyntaxException((new StringBuilder()).append("duplicate key: ").append(obj1).toString());
            }
        }

        jsonreader.endArray();
        return map;
    }
    jsonreader.beginObject();
    while (jsonreader.hasNext()) 
    {
        JsonReaderInternalAccess.INSTANCE.promoteNameToValue(jsonreader);
        Object obj = b.read(jsonreader);
        if (map.put(obj, c.read(jsonreader)) != null)
        {
            throw new JsonSyntaxException((new StringBuilder()).append("duplicate key: ").append(obj).toString());
        }
    }
    jsonreader.endObject();
    return map;
}
 
Example 18
Source File: ECMAScriptDateAdapter.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Date read(JsonReader in) throws IOException {
    try {
        if (in.peek().equals(JsonToken.NULL)) {
            in.nextNull();
            return null;
        }
        String date = in.nextString();
        return format.parse(date);
    }
    catch (ParseException e) {
        throw new JsonParseException(e);
    }
}
 
Example 19
Source File: ByteArrayAdapter.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public byte[] read ( final JsonReader reader ) throws IOException
{
    if ( reader.peek () == JsonToken.NULL )
    {
        reader.nextNull ();
        return null;
    }

    final String data = reader.nextString ();

    return Base64.getDecoder ().decode ( data );
}
 
Example 20
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Message read(JsonReader in) throws IOException, JsonIOException, JsonSyntaxException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	
	in.beginObject();
	String jsonrpc = null, method = null;
	Either<String, Number> id = null;
	Object rawParams = null;
	Object rawResult = null;
	ResponseError responseError = null;
	try {
		
		while (in.hasNext()) {
			String name = in.nextName();
			switch (name) {
			case "jsonrpc": {
				jsonrpc = in.nextString();
				break;
			}
			case "id": {
				if (in.peek() == JsonToken.NUMBER)
					id = Either.forRight(in.nextInt());
				else
					id = Either.forLeft(in.nextString());
				break;
			}
			case "method": {
				method = in.nextString();
				break;
			}
			case "params": {
				rawParams = parseParams(in, method);
				break;
			}
			case "result": {
				rawResult = parseResult(in, id != null ? id.get().toString() : null);
				break;
			}
			case "error": {
				responseError = gson.fromJson(in, ResponseError.class);
				break;
			}
			default:
				in.skipValue();
			}
		}
		Object params = parseParams(rawParams, method);
		Object result = parseResult(rawResult, id != null ? id.get().toString() : null);
		
		in.endObject();
		return createMessage(jsonrpc, id, method, params, result, responseError);
		
	} catch (JsonSyntaxException | MalformedJsonException | EOFException exception) {
		if (id != null || method != null) {
			// Create a message and bundle it to an exception with an issue that wraps the original exception
			Message message = createMessage(jsonrpc, id, method, rawParams, rawResult, responseError);
			MessageIssue issue = new MessageIssue("Message could not be parsed.", ResponseErrorCode.ParseError.getValue(), exception);
			throw new MessageIssueException(message, issue);
		} else {
			throw exception;
		}
	}
}