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

The following examples show how to use com.google.gson.stream.JsonToken#NULL . 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: 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 2
Source File: Gson.java    From letv with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
    if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
        return TypeAdapters.LONG;
    }
    return new TypeAdapter<Number>() {
        public Number read(JsonReader in) throws IOException {
            if (in.peek() != JsonToken.NULL) {
                return Long.valueOf(in.nextLong());
            }
            in.nextNull();
            return null;
        }

        public void write(JsonWriter out, Number value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(value.toString());
            }
        }
    };
}
 
Example 3
Source File: Gson.java    From gson with Apache License 2.0 6 votes vote down vote up
private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
  if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
    return TypeAdapters.LONG;
  }
  return new TypeAdapter<Number>() {
    @Override public Number read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextLong();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      out.value(value.toString());
    }
  };
}
 
Example 4
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 6 votes vote down vote up
private JsonLdContext readContextDef(JsonReader reader) throws IOException {
  reader.beginObject();
  JsonLdContext.Builder contextBuilder = JsonLdFactory.newContextBuilder();
  while (reader.hasNext()) {
    String key = reader.nextName();
    if (!JsonLdConstants.BASE.equals(key)) {
      throw new JsonLdSyntaxException(
          String.format("Unsupported '%s' in JSON-LD context", key));
    }
    JsonToken valueToken = reader.peek();
    if (valueToken == JsonToken.STRING) {
      contextBuilder.setBase(reader.nextString());
    } else if (valueToken == JsonToken.NULL) {
      reader.nextNull();
      contextBuilder.setBase(null);
    } else {
      throw new JsonLdSyntaxException(
          String.format("The value of @base is '%s', should be a string", valueToken));
    }
  }
  reader.endObject();
  return contextBuilder.build();
}
 
Example 5
Source File: WordTimingTypeAdapter.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public WordTiming read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  final WordTiming wordTiming = new WordTiming();
  in.beginArray();

  if (in.peek() == JsonToken.STRING) {
    wordTiming.setWord(in.nextString());
  }
  if (in.peek() == JsonToken.NUMBER) {
    wordTiming.setStartTime(in.nextDouble());
  }
  if (in.peek() == JsonToken.NUMBER) {
    wordTiming.setEndTime(in.nextDouble());
  }

  in.endArray();
  return wordTiming;
}
 
Example 6
Source File: JsonPropertyConsumer.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
private Object readSimpleProperty(final JsonReader reader, final EntityPropertyInfo entityPropertyInfo, final Object typeMapping) throws EdmException, EntityProviderException, IOException {
  final EdmSimpleType type = (EdmSimpleType) entityPropertyInfo.getType();
  Object value = null;
  final JsonToken tokenType = reader.peek();
  if (tokenType == JsonToken.NULL) {
    reader.nextNull();
  } else {
    switch (EdmSimpleTypeKind.valueOf(type.getName())) {
    case Boolean:
      if (tokenType == JsonToken.BOOLEAN) {
        value = reader.nextBoolean();
        value = value.toString();
      } else {
        throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName()));
      }
      break;
    case Byte:
    case SByte:
    case Int16:
    case Int32:
      if (tokenType == JsonToken.NUMBER) {
        value = reader.nextInt();
        value = value.toString();
      } else {
        throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName()));
      }
      break;
    default:
      if (tokenType == JsonToken.STRING) {
        value = reader.nextString();
      } else {
        throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY_VALUE.addContent(entityPropertyInfo.getName()));
      }
      break;
    }
  }

  final Class<?> typeMappingClass = typeMapping == null ? type.getDefaultType() : (Class<?>) typeMapping;
  return type.valueOfString((String) value, EdmLiteralKind.JSON, entityPropertyInfo.getFacets(), typeMappingClass);
}
 
Example 7
Source File: Base64TypeAdapter.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] read(JsonReader in) throws IOException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return new byte[0];
	} else {
		String data = in.nextString();
		return Base64.getDecoder().decode(data);
	}
}
 
Example 8
Source File: GsonJsonMarshallerFactory.java    From softlayer-java with MIT License 5 votes vote down vote up
@Override
public Entity read(JsonReader in) throws IOException {
    // We are allowed to assume that the first property is complexType always. This allows us to maintain
    //  a streaming reader and is very important.
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    in.beginObject();
    if (!"complexType".equals(in.nextName())) {
        throw new RuntimeException("Expected 'complexType' as first property");
    }
    String apiTypeName = in.nextString();
    // If the API type is unrecognized by us (i.e. it's a new type), we just use the type
    //  we're an adapter for. So if we have SoftLayer_Something and a newer release of the
    //  API has a type extending it but we don't have a generated class for it, it will get
    //  properly serialized to a SoftLayer_Something.
    // If the API returns a type that isn't the same or a subtype of the type class,
    //  try as best we can to fit the data within the type class.
    Class<? extends Entity> clazz = typeClasses.get(apiTypeName);
    Entity result;
    if (clazz == null || !typeClass.isAssignableFrom(clazz)) {
        result = readForThisType(in);
    } else {
        result = ((EntityTypeAdapter) gson.getAdapter(clazz)).readForThisType(in);
    }
    in.endObject();
    return result;
}
 
Example 9
Source File: TypeAdapters.java    From letv with 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 10
Source File: LenientDateTypeAdapter.java    From pf4j-update with Apache License 2.0 5 votes vote down vote up
@Override
public Date read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    return deserializeToDate(in.nextString());
}
 
Example 11
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 in.nextDouble();
}
 
Example 12
Source File: RealSandboxfs02Process.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Waits for a single response from sandboxfs and returns it.
 *
 * @param input the stream connected to sandboxfs's stdout
 * @return the response obtained from the stream
 * @throws IOException if sandboxfs fails to read from the stream for any reason, including EOF
 */
private static Response readResponse(JsonReader input) throws IOException {
  input.beginObject();
  String id = null;
  String error = null;
  while (input.hasNext()) {
    String name = input.nextName();
    switch (name) {
      case "error":
        if (input.peek() == JsonToken.NULL) {
          input.nextNull();
        } else {
          checkState(error == null);
          error = input.nextString();
        }
        break;

      case "id":
        if (input.peek() == JsonToken.NULL) {
          input.nextNull();
        } else {
          checkState(id == null);
          id = input.nextString();
        }
        break;

      default:
        throw new IOException("Invalid field name in response: " + name);
    }
  }
  input.endObject();
  return new Response(id, error);
}
 
Example 13
Source File: DateAdapters.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDateTime read(JsonReader in) throws IOException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	String v = in.nextString();
	return SumkDate.of(v).toLocalDateTime();
}
 
Example 14
Source File: FileAdapter.java    From neural-style-gui with GNU General Public License v3.0 5 votes vote down vote up
public File read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }
    return new File(reader.nextString());
}
 
Example 15
Source File: JsonBookmarkCollection.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected String readNext(final String name, final JsonReader reader) throws IOException {
    if(reader.peek() != JsonToken.NULL) {
        return reader.nextString();
    }
    else {
        reader.skipValue();
        log.warn(String.format("No value for key %s", name));
        return null;
    }
}
 
Example 16
Source File: DayOfWeekAdapter.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Override
public DayOfWeek read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

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

    switch (day) {
      case 0:
        return DayOfWeek.SUNDAY;
      case 1:
        return DayOfWeek.MONDAY;
      case 2:
        return DayOfWeek.TUESDAY;
      case 3:
        return DayOfWeek.WEDNESDAY;
      case 4:
        return DayOfWeek.THURSDAY;
      case 5:
        return DayOfWeek.FRIDAY;
      case 6:
        return DayOfWeek.SATURDAY;
    }
  }

  return DayOfWeek.UNKNOWN;
}
 
Example 17
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public String read(JsonReader in) throws IOException {
    JsonToken peek = in.peek();
    if (peek == JsonToken.NULL) {
        in.nextNull();
        return null;
    } else if (peek == JsonToken.BOOLEAN) {
        return Boolean.toString(in.nextBoolean());
    } else {
        return in.nextString();
    }
}
 
Example 18
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 19
Source File: CollectionTypeAdapterFactory.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override public Collection<E> read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  Collection<E> collection = constructor.construct();
  in.beginArray();
  while (in.hasNext()) {
    E instance = elementTypeAdapter.read(in);
    collection.add(instance);
  }
  in.endArray();
  return collection;
}
 
Example 20
Source File: StructuredJsonExamplesProvider.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Namespace readNamespace(long exampleNumber, JsonReader jsonReader) throws IOException {
	jsonReader.beginObject();

	StructuredExample.Namespace.NamespaceBuilder nsBuilder = new StructuredExample.Namespace.NamespaceBuilder();

	boolean nameRead = false, scalingFactorRead = false, featuresRead = false;

	while (jsonReader.hasNext()) {

		String propertyNameOriginal = jsonReader.nextName();
		String propertyName = propertyNameOriginal.trim().toLowerCase();

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

			if (nameRead) {

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

			if (jsonReader.peek() == JsonToken.NULL)
				jsonReader.nextNull();
			else {
				String namespace = jsonReader.nextString();
				nsBuilder.setName(namespace);
			}
			nameRead = true;
		}
		else if (propertyName.equals(StructuredJsonPropertyNames.NAMESPACE_SCALING_FACTOR_PROPERTY)) {

			if (scalingFactorRead) {

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

			if (jsonReader.peek() == JsonToken.NULL)
				jsonReader.nextNull();
			else {
				double scalingFactor = jsonReader.nextDouble();
				nsBuilder.setScalingFactor(Float.valueOf((float) scalingFactor));
			}
			scalingFactorRead = true;

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

			if (featuresRead) {

				throw new ExampleFormatException(exampleNumber, "The 'features' property must only appear once in a namespace!");
			}

			if (jsonReader.peek() == JsonToken.NULL) {
				jsonReader.nextNull();
			}
			else {

				jsonReader.beginArray();

				int numFeaturesAdded = 0;

				while (jsonReader.hasNext()) {
					readFeatureIntoNamespace(exampleNumber, nsBuilder, jsonReader);

					numFeaturesAdded++;

					if (maxNumberOfFeaturesPerNamespace > 0 && maxNumberOfFeaturesPerNamespace < Integer.MAX_VALUE && numFeaturesAdded > maxNumberOfFeaturesPerNamespace) {
						throw new ExampleFormatException(exampleNumber, "The maximum number of features per namespace, " + maxNumberOfFeaturesPerNamespace + " was exceeded!");
					}
				}

				jsonReader.endArray();

			}
			featuresRead = true;

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

	jsonReader.endObject();

	return nsBuilder.build();
}