List of usage examples for com.google.gson.stream JsonReader endArray
public void endArray() throws IOException
From source file:com.getperka.flatpack.fast.JavaDialect.java
License:Apache License
/** * If {@value #concreteTypeMapFile} is defined, load the file into {@link #concreteTypeMap}. *//* w ww. j a v a 2 s. c o m*/ private void loadConcreteTypeMap() throws IOException { if (baseTypeArrayFile != null) { JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(baseTypeArrayFile), UTF8)); reader.setLenient(true); reader.beginArray(); while (reader.hasNext()) { baseTypes.add(reader.nextString()); } reader.endArray(); reader.close(); } }
From source file:com.getperka.flatpack.Unpacker.java
License:Apache License
private <T> FlatPackEntity<T> unpack(Type returnType, JsonReader reader, Principal principal) throws IOException { // Hold temporary state for deserialization DeserializationContext context = contexts.get(); /*/*from ww w . j a va 2 s .co m*/ * Decoding is done as a two-pass operation since the runtime type of an allocated object cannot * be swizzled. The per-entity data is held as a semi-reified JsonObject to be passed off to a * Codex. */ Map<HasUuid, JsonObject> entityData = FlatPackCollections.mapForIteration(); // Used to populate the entityData map JsonParser jsonParser = new JsonParser(); /* * The reader is placed in lenient mode as an aid to developers, however all output will be * strictly formatted. */ reader.setLenient(true); // The return value @SuppressWarnings("unchecked") FlatPackEntity<T> toReturn = (FlatPackEntity<T>) FlatPackEntity.create(returnType, null, principal); // Stores the single, top-level value in the payload for two-pass reification JsonElement value = null; if (reader.peek().equals(JsonToken.NULL)) { return toReturn; } reader.beginObject(); while (JsonToken.NAME.equals(reader.peek())) { String name = reader.nextName(); if ("data".equals(name)) { // data : { "fooEntity" : [ { ... }, { ... } ] reader.beginObject(); while (JsonToken.NAME.equals(reader.peek())) { // Turn "fooEntity" into the actual FooEntity class String simpleName = reader.nextName(); Class<? extends HasUuid> clazz = typeContext.getClass(simpleName); if (clazz == null) { if (ignoreUnresolvableTypes) { reader.skipValue(); continue; } else { throw new UnsupportedOperationException("Cannot resolve type " + simpleName); } } else if (Modifier.isAbstract(clazz.getModifiers())) { throw new UnsupportedOperationException( "A subclass of " + simpleName + " must be used instead"); } context.pushPath("allocating " + simpleName); try { // Find the Codex for the requested entity type EntityCodex<?> codex = (EntityCodex<?>) typeContext.getCodex(clazz); // Take the n-many property objects and stash them for later decoding reader.beginArray(); while (!JsonToken.END_ARRAY.equals(reader.peek())) { JsonObject chunk = jsonParser.parse(reader).getAsJsonObject(); HasUuid entity = codex.allocate(chunk, context); toReturn.addExtraEntity(entity); entityData.put(entity, chunk.getAsJsonObject()); } reader.endArray(); } finally { context.popPath(); } } reader.endObject(); } else if ("errors".equals(name)) { // "errors" : { "path" : "problem", "path2" : "problem2" } reader.beginObject(); while (JsonToken.NAME.equals(reader.peek())) { String path = reader.nextName(); if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) { toReturn.addError(path, reader.nextString()); } else { reader.skipValue(); } } reader.endObject(); } else if ("metadata".equals(name)) { reader.beginArray(); while (!JsonToken.END_ARRAY.equals(reader.peek())) { EntityMetadata meta = new EntityMetadata(); JsonObject metaElement = jsonParser.parse(reader).getAsJsonObject(); metaCodex.get().readProperties(meta, metaElement, context); toReturn.addMetadata(meta); } reader.endArray(); } else if ("value".equals(name)) { // Just stash the value element in case it occurs first value = jsonParser.parse(reader); } else if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) { // Save off any other simple properties toReturn.putExtraData(name, reader.nextString()); } else { // Ignore random other entries reader.skipValue(); } } reader.endObject(); reader.close(); for (Map.Entry<HasUuid, JsonObject> entry : entityData.entrySet()) { HasUuid entity = entry.getKey(); EntityCodex<HasUuid> codex = (EntityCodex<HasUuid>) typeContext.getCodex(entity.getClass()); codex.readProperties(entity, entry.getValue(), context); } @SuppressWarnings("unchecked") Codex<T> returnCodex = (Codex<T>) typeContext.getCodex(toReturn.getType()); toReturn.withValue(returnCodex.read(value, context)); for (Map.Entry<UUID, String> entry : context.getWarnings().entrySet()) { toReturn.addWarning(entry.getKey().toString(), entry.getValue()); } // Process metadata for (EntityMetadata meta : toReturn.getMetadata()) { if (meta.isPersistent()) { HasUuid entity = context.getEntity(meta.getUuid()); if (entity instanceof PersistenceAware) { ((PersistenceAware) entity).markPersistent(); } } } context.runPostWork(); context.close(); return toReturn; }
From source file:com.github.filosganga.geogson.gson.PositionsAdapter.java
License:Apache License
private Positions parsePositions(JsonReader in) throws IOException { Optional<Positions> parsed = Optional.absent(); if (in.peek() != JsonToken.BEGIN_ARRAY) { throw new IllegalArgumentException("The given json is not a valid positions"); }/*from w ww. j a v a 2s . c om*/ in.beginArray(); if (in.peek() == JsonToken.NUMBER) { parsed = Optional.of(parseSinglePosition(in)); } else if (in.peek() == JsonToken.BEGIN_ARRAY) { while (in.hasNext()) { Positions thisPositions = parsePositions(in); // fix bug #30: according to the recursion (i.e. the array structure; // recognize that we came from a recursion because no parsed has no // value yet): convert the already parsed Positions to the // LinearPositions/AreaPositions matching the recursion level if (parsed.equals(Optional.absent()) && thisPositions instanceof LinearPositions) { AreaPositions areaPositions = new AreaPositions( ImmutableList.of((LinearPositions) thisPositions)); parsed = Optional.of((Positions) areaPositions); } else if (parsed.equals(Optional.absent()) && thisPositions instanceof AreaPositions) { MultiDimensionalPositions multiPositions = new MultiDimensionalPositions( ImmutableList.of((AreaPositions) thisPositions)); parsed = Optional.of((Positions) multiPositions); } else { // mergeFn() does all the rest, if parsed has a value parsed = parsed.transform(mergeFn(thisPositions)).or(Optional.of(thisPositions)); } } } in.endArray(); return parsed.orNull(); }
From source file:com.github.gv2011.jsong.JsongAdapter.java
License:Open Source License
private JsonNode deserialize(final JsonFactoryImp jf, final JsonReader in) { return call(() -> { switch (in.peek()) { case STRING: return jf.primitive(in.nextString()); case NUMBER: return jf.primitive(new BigDecimal(in.nextString())); case BOOLEAN: return jf.primitive(in.nextBoolean()); case NULL: in.nextNull();// ww w . ja v a 2s. co m return jf.jsonNull(); case BEGIN_ARRAY: in.beginArray(); final JsonList list = XStream.fromIterator(new It(jf, in)).collect(jf.toJsonList()); in.endArray(); return list; case BEGIN_OBJECT: in.beginObject(); final JsonObject obj = XStream.fromIterator(new Itm(jf, in)).collect(jf.toJsonObject()); in.endObject(); return obj; case NAME: case END_DOCUMENT: case END_OBJECT: case END_ARRAY: default: throw new IllegalArgumentException(); } }); }
From source file:com.github.kevinsawicki.halligan.Resource.java
License:Open Source License
/** * Parse resources from current value//from w w w . j a v a 2 s.co m * * @param reader * @throws IOException */ protected void parseResources(final JsonReader reader) throws IOException { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); JsonToken next = reader.peek(); switch (next) { case BEGIN_OBJECT: resources.put(name, Collections.singletonList(createResource().parse(reader))); break; case BEGIN_ARRAY: reader.beginArray(); List<Resource> entries = new ArrayList<Resource>(); while (reader.peek() == BEGIN_OBJECT) entries.add(createResource().parse(reader)); reader.endArray(); resources.put(name, entries); break; default: throw new IOException( "_embedded object value is a " + next.name() + " and must be an array or object"); } } reader.endObject(); }
From source file:com.github.lindenb.gatkui.Json2Xml.java
License:Open Source License
private void parseArray(String label, JsonReader r) throws Exception { w.writeStartElement(NS, "array"); if (label != null) w.writeAttribute("name", label); for (;;) {/* w w w . java 2 s. c om*/ if (r.peek() == JsonToken.END_ARRAY) break; parse(null, r); } w.writeEndElement(); r.endArray(); }
From source file:com.google.maps.internal.GeolocationResponseAdapter.java
License:Open Source License
@Override public GeolocationApi.Response read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull();/* w w w . j a v a 2 s. co m*/ return null; } GeolocationApi.Response response = new GeolocationApi.Response(); LatLngAdapter latLngAdapter = new LatLngAdapter(); reader.beginObject(); // opening { while (reader.hasNext()) { String name = reader.nextName(); // two different objects could be returned a success object containing "location" and "accuracy" // keys or an error object containing an "error" key if (name.equals("location")) { // we already have a parser for the LatLng object so lets use that response.location = latLngAdapter.read(reader); } else if (name.equals("accuracy")) { response.accuracy = reader.nextDouble(); } else if (name.equals("error")) { reader.beginObject(); // the error key leads to another object... while (reader.hasNext()) { String errName = reader.nextName(); // ...with keys "errors", "code" and "message" if (errName.equals("code")) { response.code = reader.nextInt(); } else if (errName.equals("message")) { response.message = reader.nextString(); } else if (errName.equals("errors")) { reader.beginArray(); // its plural because its an array of errors... while (reader.hasNext()) { reader.beginObject();// ...and each error array element is an object... while (reader.hasNext()) { errName = reader.nextName(); // ...with keys "reason", "domain", "debugInfo", "location", "locationType", and "message" (again) if (errName.equals("reason")) { response.reason = reader.nextString(); } else if (errName.equals("domain")) { response.domain = reader.nextString(); } else if (errName.equals("debugInfo")) { response.debugInfo = reader.nextString(); } else if (errName.equals("message")) { // have this already reader.nextString(); } else if (errName.equals("location")) { reader.nextString(); } else if (errName.equals("locationType")) { reader.nextString(); } } reader.endObject(); } reader.endArray(); } } reader.endObject(); // closing } } } reader.endObject(); return response; }
From source file:com.google.samples.apps.iosched.sync.userdata.util.UserActionHelper.java
License:Open Source License
public static List<UserAction> deserializeUserActions(String str) { try {/* w ww .j a v a 2s .c o m*/ ArrayList<UserAction> actions = new ArrayList<UserAction>(); JsonReader reader = new JsonReader(new StringReader(str)); reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); UserAction action = new UserAction(); while (reader.hasNext()) { String key = reader.nextName(); if ("type".equals(key)) { action.type = UserAction.TYPE.valueOf(reader.nextString()); } else if ("id".equals(key)) { action.sessionId = reader.nextString(); } else { throw new RuntimeException("Invalid key " + key + " in serialized UserAction: " + str); } } reader.endObject(); actions.add(action); } reader.endArray(); return actions; } catch (IOException ex) { throw new RuntimeException("Error deserializing UserActions: " + str, ex); } }
From source file:com.google.samples.apps.iosched.sync.userdata.util.UserDataHelper.java
License:Open Source License
static public Set<String> fromString(String str) { TreeSet<String> result = new TreeSet<String>(); if (str == null || str.isEmpty()) { return result; }//from w ww . jav a2 s . c o m try { JsonReader reader = new JsonReader(new StringReader(str)); reader.beginObject(); while (reader.hasNext()) { String key = reader.nextName(); if (JSON_STARRED_SESSIONS_KEY.equals(key)) { reader.beginArray(); while (reader.hasNext()) { result.add(reader.nextString()); } reader.endArray(); } else { reader.skipValue(); } } reader.endObject(); reader.close(); } catch (Exception ex) { Log.w(TAG, "Ignoring invalid remote content.", ex); return null; } return result; }
From source file:com.greensopinion.finance.services.persistence.CategoriesTypeAdapter.java
License:Apache License
@Override public Categories read(JsonReader reader) throws IOException { reader.beginObject();//ww w .j a v a 2s . c o m checkState(NAME_CATEGORIES.equals(reader.nextName())); reader.beginArray(); ImmutableList.Builder<Category> elements = ImmutableList.<Category>builder(); while (reader.hasNext()) { if (reader.peek() == JsonToken.BEGIN_OBJECT) { elements.add(gson.getAdapter(Category.class).read(reader)); } else { elements.add(readCategory(reader.nextString())); } } reader.endArray(); reader.endObject(); return new Categories(elements.build()); }