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

The following examples show how to use com.google.gson.stream.JsonReader#nextLong() . 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: NodeLayoutStore.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private static NodeLayoutInfo parseLayoutInfo(
		JsonReader r) throws IOException {
	NodeLayoutInfo info = new NodeLayoutInfo();
	r.beginObject();
	r.nextName();
	info.id = r.nextLong();
	r.nextName();
	info.x = r.nextInt();
	r.nextName();
	info.y = r.nextInt();
	r.nextName();
	info.minimized = r.nextBoolean();
	r.nextName();
	info.expandedLeft = r.nextBoolean();
	r.nextName();
	info.expandedRight = r.nextBoolean();
	r.nextName();
	info.marked = r.nextBoolean();
	r.endObject();
	return info;
}
 
Example 2
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 3
Source File: ConversionService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Date read(JsonReader reader) throws IOException {
   if (reader.peek() == JsonToken.NULL) {
      return null;
   }

   return new Date(reader.nextLong());
}
 
Example 4
Source File: DateTypeAdapter.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Date read(JsonReader in) throws IOException {
	if(JsonToken.NULL.equals(in.peek())) {
		in.nextNull();
		return null;
	}
	else {
	   try {
	      return new Date(in.nextLong());
	   }
	   catch(NumberFormatException e) {
	      return new Date((long) in.nextDouble());
	   }
	}
}
 
Example 5
Source File: DateTypeAdapter.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Date read(JsonReader in) throws IOException {
	if(JsonToken.NULL.equals(in.peek())) {
		in.nextNull();
		return null;
	}
	else {
		return new Date(in.nextLong());
	}
}
 
Example 6
Source File: TypeAdapters.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Number read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  try {
    return in.nextLong();
  } catch (NumberFormatException e) {
    throw new JsonSyntaxException(e);
  }
}
 
Example 7
Source File: DateAdapter.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Date read(JsonReader in) throws IOException {
	if (in != null) {
		return new Date(in.nextLong());
	} else {
		return null;
	}
}
 
Example 8
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 9
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 10
Source File: BagOfPrimitivesDeserializationBenchmark.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * Benchmark to measure deserializing objects by hand
 */
public void timeBagOfPrimitivesStreaming(int reps) throws IOException {
  for (int i=0; i<reps; ++i) {
    StringReader reader = new StringReader(json);
    JsonReader jr = new JsonReader(reader);
    jr.beginObject();
    long longValue = 0;
    int intValue = 0;
    boolean booleanValue = false;
    String stringValue = null;
    while(jr.hasNext()) {
      String name = jr.nextName();
      if (name.equals("longValue")) {
        longValue = jr.nextLong();
      } else if (name.equals("intValue")) {
        intValue = jr.nextInt();
      } else if (name.equals("booleanValue")) {
        booleanValue = jr.nextBoolean();
      } else if (name.equals("stringValue")) {
        stringValue = jr.nextString();
      } else {
        throw new IOException("Unexpected name: " + name);
      }
    }
    jr.endObject();
    new BagOfPrimitives(longValue, intValue, booleanValue, stringValue);
  }
}
 
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;
  }
  try {
    return in.nextLong();
  } catch (NumberFormatException e) {
    throw new JsonSyntaxException(e);
  }
}
 
Example 12
Source File: Adapters.java    From salt-netapi-client with MIT License 4 votes vote down vote up
@Override
public Long read(JsonReader in) throws IOException {
    return in.nextLong();
}
 
Example 13
Source File: FoodReader.java    From TFC2 with GNU General Public License v3.0 4 votes vote down vote up
private FoodJSON readFood(JsonReader reader) throws IOException
{
	String name = "";
	int meta = 0;
	long time = -1;
	List<FoodGroupPair> fg = new ArrayList<FoodGroupPair>();
	boolean edible = true;

	reader.beginObject();
	while(reader.hasNext())
	{
		String key = reader.nextName();
		if(key.equals("name"))
		{
			name = reader.nextString();
			if(name.contains(" "))
			{
				String[] s = name.split(" ");
				name = s[0];
				meta = Integer.parseInt(s[1]);
			}
		}
		else if(key.equals("decay"))
			time = reader.nextLong();
		else if(key.equals("foodgroup"))
		{
			if(reader.peek() == JsonToken.BEGIN_OBJECT)
			{
				reader.beginObject();
				while(reader.hasNext())
				{
					fg.add(new FoodGroupPair(EnumFoodGroup.valueOf(reader.nextName()), (float)reader.nextDouble()));
				}
				reader.endObject();
			}
			else
				fg.add(new FoodGroupPair(EnumFoodGroup.valueOf(reader.nextString()), 100f));
		}
		else if(key.equals("edible"))
			edible = reader.nextBoolean();
		else
			reader.skipValue();
	}
	reader.endObject();


	return new FoodJSON(name, meta, time, fg, edible);

}
 
Example 14
Source File: JsonAdapterAnnotationOnFieldsTest.java    From gson with Apache License 2.0 4 votes vote down vote up
@Override public Long read(JsonReader in) throws IOException {
  return in.nextLong();
}
 
Example 15
Source File: ResponseAdapter.java    From feign with Apache License 2.0 4 votes vote down vote up
/**
 * the wikipedia api doesn't use json arrays, rather a series of nested objects.
 */
@Override
public WikipediaExample.Response<X> read(JsonReader reader) throws IOException {
  WikipediaExample.Response<X> pages = new WikipediaExample.Response<X>();
  reader.beginObject();
  while (reader.hasNext()) {
    String nextName = reader.nextName();
    if ("query".equals(nextName)) {
      reader.beginObject();
      while (reader.hasNext()) {
        if (query().equals(reader.nextName())) {
          reader.beginObject();
          while (reader.hasNext()) {
            // each element is in form: "id" : { object }
            // this advances the pointer to the value and skips the key
            reader.nextName();
            reader.beginObject();
            pages.add(build(reader));
            reader.endObject();
          }
          reader.endObject();
        } else {
          reader.skipValue();
        }
      }
      reader.endObject();
    } else if ("continue".equals(nextName)) {
      reader.beginObject();
      while (reader.hasNext()) {
        if ("gsroffset".equals(reader.nextName())) {
          pages.nextOffset = reader.nextLong();
        } else {
          reader.skipValue();
        }
      }
      reader.endObject();
    } else {
      reader.skipValue();
    }
  }
  reader.endObject();
  return pages;
}
 
Example 16
Source File: ChannelReader.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
private Map<MetaKey, CacheEntryInformation> readCacheEntries ( final JsonReader jr ) throws IOException
{
    final Map<MetaKey, CacheEntryInformation> result = new HashMap<> ();

    jr.beginObject ();
    while ( jr.hasNext () )
    {
        final String entryName = jr.nextName ();
        jr.beginObject ();

        String name = null;
        Long size = null;
        String mimeType = null;
        Instant timestamp = null;

        while ( jr.hasNext () )
        {
            final String ele = jr.nextName ();
            switch ( ele )
            {
                case "name":
                    name = jr.nextString ();
                    break;
                case "size":
                    size = jr.nextLong ();
                    break;
                case "mimeType":
                    mimeType = jr.nextString ();
                    break;
                case "timestamp":
                    timestamp = readTime ( jr );
                    break;
                default:
                    jr.skipValue ();
                    break;
            }
        }

        if ( name == null || size == null || mimeType == null || timestamp == null )
        {
            throw new IOException ( "Invalid format" );
        }

        jr.endObject ();

        final MetaKey key = MetaKey.fromString ( entryName );

        result.put ( key, new CacheEntryInformation ( key, name, size, mimeType, timestamp ) );
    }
    jr.endObject ();

    return result;
}
 
Example 17
Source File: ChannelReader.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
private Map<String, ArtifactInformation> readArtifacts ( final JsonReader jr ) throws IOException
{
    jr.beginObject ();

    final Map<String, ArtifactInformation> result = new HashMap<> ();

    while ( jr.hasNext () )
    {
        final String id = jr.nextName ();
        jr.beginObject ();

        String name = null;
        Long size = null;
        Instant creationTimestamp = null;
        String parentId = null;
        Set<String> childIds = Collections.emptySet ();
        Set<String> facets = Collections.emptySet ();
        String virtualizerAspectId = null;
        List<ValidationMessage> validationMessages = Collections.emptyList ();
        Map<MetaKey, String> extractedMetaData = Collections.emptyMap ();
        Map<MetaKey, String> providedMetaData = Collections.emptyMap ();

        while ( jr.hasNext () )
        {
            final String ele = jr.nextName ();
            switch ( ele )
            {
                case "name":
                    name = jr.nextString ();
                    break;
                case "size":
                    size = jr.nextLong ();
                    break;
                case "date":
                    creationTimestamp = readTime ( jr );
                    break;
                case "parentId":
                    parentId = jr.nextString ();
                    break;
                case "childIds":
                    childIds = readSet ( jr );
                    break;
                case "facets":
                    facets = readSet ( jr );
                    break;
                case "virtualizerAspectId":
                    virtualizerAspectId = jr.nextString ();
                    break;
                case "extractedMetaData":
                    extractedMetaData = readMetadata ( jr );
                    break;
                case "providedMetaData":
                    providedMetaData = readMetadata ( jr );
                    break;
                case "validationMessages":
                    validationMessages = readValidationMessages ( jr );
                    break;
                default:
                    jr.skipValue ();
                    break;
            }
        }
        jr.endObject ();

        if ( id == null || name == null || size == null || creationTimestamp == null )
        {
            throw new IOException ( "Missing values for artifact" );
        }

        this.numberOfBytes += size;

        result.put ( id, new ArtifactInformation ( id, parentId, childIds, name, size, creationTimestamp, facets, validationMessages, providedMetaData, extractedMetaData, virtualizerAspectId ) );
    }

    jr.endObject ();

    return result;
}
 
Example 18
Source File: PrayerDataTypeAdapter.java    From android with Apache License 2.0 4 votes vote down vote up
@Override
public PrayerData read(JsonReader in) throws IOException {
    final PrayerData pd = new PrayerData();

    in.beginObject();

    while (in.hasNext()) {
        switch (in.nextName()) {
            case "provider":
                pd.setProvider(in.nextString());
                break;
            case "provider_code":
                pd.setProviderCode(in.nextString());
                break;
            case "code":
                pd.setCode(in.nextString());
                break;
            case "year":
                pd.setYear(in.nextInt());
                break;
            case "month":
                pd.setMonth(in.nextInt());
                break;
            case "place":
                pd.setLocation(in.nextString());
                break;
            case "attributes":
                in.beginObject();

                while (in.hasNext()) {
                    switch (in.nextName()) {
                        case "jakim_code":
                            in.nextString();
                            break;
                        case "jakim_source":
                            in.nextString();
                            break;
                        default:
                            in.nextString();
                    }
                }

                in.endObject();
                break;
            case "times":
                final List<List<Date>> lld = new ArrayList<>();
                in.beginArray();

                while (in.hasNext()) {
                    final List<Date> ld = new ArrayList<>();
                    in.beginArray();

                    while (in.hasNext()) {
                        final Date d = new Date(in.nextLong() * 1000);
                        ld.add(d);
                    }

                    in.endArray();

                    if (ld.size() == 6) {
                        Date subuh = ld.get(0);
                        Date syuruk = ld.get(1);
                        long subuhR = subuh.getTime();
                        long syurukR = syuruk.getTime();
                        Date imsak = new Date(subuhR - 10 * 60 * 1000);
                        Date dhuha = new Date(syurukR + ((syurukR - subuhR) / 3));

                        ld.add(0, imsak);
                        ld.add(3, dhuha);
                    }

                    lld.add(ld);
                }

                in.endArray();
                pd.setPrayerTimes(lld);
                break;
            default:
                in.skipValue();
        }
    }

    in.endObject();

    return pd;
}
 
Example 19
Source File: JSONPListParser.java    From tm4e with Eclipse Public License 1.0 4 votes vote down vote up
public T parse(InputStream contents) throws Exception {
	PList<T> pList = new PList<T>(theme);
	JsonReader reader = new JsonReader(new InputStreamReader(contents, StandardCharsets.UTF_8));
	// reader.setLenient(true);
	boolean parsing = true;
	while (parsing) {
		JsonToken nextToken = reader.peek();
		switch (nextToken) {
		case BEGIN_ARRAY:
			pList.startElement(null, "array", null, null);
			reader.beginArray();
			break;
		case END_ARRAY:
			pList.endElement(null, "array", null);
			reader.endArray();
			break;
		case BEGIN_OBJECT:
			pList.startElement(null, "dict", null, null);
			reader.beginObject();
			break;
		case END_OBJECT:
			pList.endElement(null, "dict", null);
			reader.endObject();
			break;
		case NAME:
			String lastName = reader.nextName();
			pList.startElement(null, "key", null, null);
			pList.characters(lastName.toCharArray(), 0, lastName.length());
			pList.endElement(null, "key", null);
			break;
		case NULL:
			reader.nextNull();
			break;
		case BOOLEAN:
			reader.nextBoolean();
			break;
		case NUMBER:
			reader.nextLong();
			break;
		case STRING:
			String value = reader.nextString();
			pList.startElement(null, "string", null, null);
			pList.characters(value.toCharArray(), 0, value.length());
			pList.endElement(null, "string", null);
			break;
		case END_DOCUMENT:
			parsing = false;
			break;
		default:
			break;
		}
	}
	reader.close();
	return pList.getResult();
}
 
Example 20
Source File: TraceEvent.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static TraceEvent createFromJsonReader(JsonReader reader) throws IOException {
  String category = null;
  String name = null;
  Duration timestamp = null;
  Duration duration = null;
  long threadId = -1;
  String primaryOutputPath = null;
  String targetLabel = null;

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "cat":
        category = reader.nextString();
        break;
      case "name":
        name = reader.nextString();
        break;
      case "ts":
        // Duration has no microseconds :-/.
        timestamp = Duration.ofNanos(reader.nextLong() * 1000);
        break;
      case "dur":
        duration = Duration.ofNanos(reader.nextLong() * 1000);
        break;
      case "tid":
        threadId = reader.nextLong();
        break;
      case "out":
        primaryOutputPath = reader.nextString();
        break;
      case "args":
        ImmutableMap<String, Object> args = parseMap(reader);
        Object target = args.get("target");
        targetLabel = target instanceof String ? (String) target : null;
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();
  return TraceEvent.create(
      category, name, timestamp, duration, threadId, primaryOutputPath, targetLabel);
}