List of usage examples for com.google.gson.stream JsonReader endObject
public void endObject() throws IOException
From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java
License:Open Source License
/** * This method checks the hardcoded URL and downloads a list of patches to be checked * * @param prefAdapter The preference adapter is used to get the last update time * @return An ArrayList of String[] which contains the {Name, URL, Set Code} for each available patch * @throws IOException Thrown if something goes wrong with the InputStream from the web *///from ww w . ja v a 2 s . co m public ArrayList<String[]> readUpdateJsonStream(PreferenceAdapter prefAdapter) throws IOException { ArrayList<String[]> patchInfo = new ArrayList<>(); URL update; String label; String label2; update = new URL(PATCHES_URL); InputStreamReader isr = new InputStreamReader(update.openStream(), "ISO-8859-1"); JsonReader reader = new JsonReader(isr); reader.beginObject(); while (reader.hasNext()) { label = reader.nextName(); if (label.equals("Date")) { String lastUpdate = prefAdapter.getLastUpdate(); mCurrentPatchDate = reader.nextString(); if (lastUpdate.equals(mCurrentPatchDate)) { reader.close(); return null; } } else if (label.equals("Patches")) { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); String[] setData = new String[3]; while (reader.hasNext()) { label2 = reader.nextName(); switch (label2) { case "Name": setData[SET_NAME] = reader.nextString(); break; case "URL": setData[SET_URL] = reader.nextString(); break; case "Code": setData[SET_CODE] = reader.nextString(); break; } } patchInfo.add(setData); reader.endObject(); } reader.endArray(); } } reader.endObject(); reader.close(); return patchInfo; }
From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java
License:Open Source License
/** * Parses the legality file and populates the database with the different formats, their respective sets, and their * banned and restricted lists//from w w w .j a v a 2 s . co m * * @param prefAdapter The preference adapter is used to get the last update time * @return An object with all of the legal info, to be added to the database in one fell swoop * @throws IOException Thrown if something goes wrong with the InputStream * @throws com.gelakinetic.mtgfam.helpers.database.FamiliarDbException Thrown if something goes wrong with database writing */ public LegalInfo readLegalityJsonStream(PreferenceAdapter prefAdapter) throws IOException, FamiliarDbException { LegalInfo legalInfo = new LegalInfo(); String legalSet; String bannedCard; String restrictedCard; String formatName; String jsonArrayName; String jsonTopLevelName; URL legal = new URL(LEGALITY_URL); InputStream in = new BufferedInputStream(legal.openStream()); JsonReader reader = new JsonReader(new InputStreamReader(in, "ISO-8859-1")); reader.beginObject(); while (reader.hasNext()) { jsonTopLevelName = reader.nextName(); if (jsonTopLevelName.equalsIgnoreCase("Date")) { mCurrentRulesDate = reader.nextString(); /* compare date, maybe return, update shared prefs */ String spDate = prefAdapter.getLegalityDate(); if (spDate != null && spDate.equals(mCurrentRulesDate)) { reader.close(); return null; /* dates match, nothing new here. */ } } else if (jsonTopLevelName.equalsIgnoreCase("Formats")) { reader.beginObject(); while (reader.hasNext()) { formatName = reader.nextName(); legalInfo.formats.add(formatName); reader.beginObject(); while (reader.hasNext()) { jsonArrayName = reader.nextName(); if (jsonArrayName.equalsIgnoreCase("Sets")) { reader.beginArray(); while (reader.hasNext()) { legalSet = reader.nextString(); legalInfo.legalSets.add(new NameAndMetadata(legalSet, formatName)); } reader.endArray(); } else if (jsonArrayName.equalsIgnoreCase("Banlist")) { reader.beginArray(); while (reader.hasNext()) { bannedCard = reader.nextString(); legalInfo.bannedCards.add(new NameAndMetadata(bannedCard, formatName)); } reader.endArray(); } else if (jsonArrayName.equalsIgnoreCase("Restrictedlist")) { reader.beginArray(); while (reader.hasNext()) { restrictedCard = reader.nextString(); legalInfo.restrictedCards.add(new NameAndMetadata(restrictedCard, formatName)); } reader.endArray(); } } reader.endObject(); } reader.endObject(); } } reader.endObject(); reader.close(); return legalInfo; }
From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java
License:Open Source License
/** * This method parses the mapping between set codes and the names TCGPlayer.com uses * * @param prefAdapter The preference adapter is used to get the last update time * @param tcgNames A place to store tcg names before adding to the database * @throws IOException Thrown if something goes wrong with the InputStream *//*from w w w. ja v a 2 s . c o m*/ public void readTCGNameJsonStream(PreferenceAdapter prefAdapter, ArrayList<NameAndMetadata> tcgNames) throws IOException { URL update; String label; String label2; String name = null, code = null; update = new URL(TCG_NAMES_URL); InputStreamReader isr = new InputStreamReader(update.openStream(), "ISO-8859-1"); JsonReader reader = new JsonReader(isr); reader.beginObject(); while (reader.hasNext()) { label = reader.nextName(); if (label.equals("Date")) { String lastUpdate = prefAdapter.getLastTCGNameUpdate(); mCurrentTCGNamePatchDate = reader.nextString(); if (lastUpdate.equals(mCurrentTCGNamePatchDate)) { reader.close(); return; } } else if (label.equals("Sets")) { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { label2 = reader.nextName(); if (label2.equals("Code")) { code = reader.nextString(); } else if (label2.equals("TCGName")) { name = reader.nextString(); } } tcgNames.add(new NameAndMetadata(name, code)); reader.endObject(); } reader.endArray(); } } reader.endObject(); 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 w ww.j a v a 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.gilecode.yagson.types.TypeUtils.java
License:Apache License
private static <T> T readTypeAdvisedValueAfterType(Gson gson, JsonReader in, ReadContext ctx, Type valueType) throws IOException { T result = null;// w ww . ja va2 s . c om if (consumeValueField(in)) { // use actual type adapter instead of delegate TypeAdapter<?> typeAdapter = gson.getAdapter(TypeToken.get(valueType)); result = (T) typeAdapter.read(in, ctx); } in.endObject(); return result; }
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();// w ww . ja va2s.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
/** * Fill this resource by parsing the next object in the reader * * @param reader/*from w ww . j a va2 s .c o m*/ * @return this resource * @throws IOException */ protected Resource parse(final JsonReader reader) throws IOException { reader.beginObject(); while (reader.hasNext() && reader.peek() == NAME) { String name = reader.nextName(); if ("_links".equals(name)) parseLinks(reader); else if ("_embedded".equals(name)) parseResources(reader); else parseProperty(reader, name); } reader.endObject(); return this; }
From source file:com.github.kevinsawicki.halligan.Resource.java
License:Open Source License
/** * Parse resources from current value//www . j a v a 2 s .c o 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 parseObject(String label, JsonReader r) throws Exception { w.writeStartElement(NS, "object"); if (label != null) w.writeAttribute("name", label); for (;;) {//from w ww. ja v a 2s. co m if (r.peek() == JsonToken.END_OBJECT) break; if (r.peek() != JsonToken.NAME) throw new IllegalStateException(r.peek().name()); String s = r.nextName(); parse(s, r); } w.writeEndElement(); r.endObject(); }
From source file:com.google.maps.internal.DateTimeAdapter.java
License:Open Source License
/** * Read a Time object from a Directions API result and convert it to a {@link DateTime}. * * <p>We are expecting to receive something akin to the following: * <pre>/*from w w w. j ava2s. c o m*/ * { * "text" : "4:27pm", * "time_zone" : "Australia/Sydney", * "value" : 1406528829 * } * </pre> */ @Override public DateTime 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 new DateTime(secondsSinceEpoch * 1000, DateTimeZone.forID(timeZoneId)); }