List of usage examples for com.google.gson.stream JsonReader nextString
public String nextString() throws IOException
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; }/* w ww . j a v a 2 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();/* w w w. j a v a 2 s. co 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()); }
From source file:com.greensopinion.finance.services.persistence.DateTypeAdapter.java
License:Apache License
@Override public Date read(JsonReader reader) throws IOException { if (reader.peek().equals(JsonToken.NULL)) { reader.nextNull();// w ww . j ava2s . c o m return null; } String value = reader.nextString(); try { return dateFormat().parse(value); } catch (ParseException e) { throw new IOException(format("Expected a date but got \"{0}\"", value)); } }
From source file:com.greensopinion.finance.services.persistence.TransactionsTypeAdapter.java
License:Apache License
@Override public Transactions read(JsonReader reader) throws IOException { reader.beginObject();//from ww w . j a va 2s . co m checkState(reader.nextName().equals(NAME_TRANSACTIONS)); reader.beginArray(); ImmutableList.Builder<Transaction> elements = ImmutableList.builder(); while (reader.hasNext()) { elements.add(readTransaction(reader.nextString())); } reader.endArray(); reader.endObject(); return new Transactions(elements.build()); }
From source file:com.gs.reladomo.serial.gson.GsonWrappedListTypedAdapter.java
License:Apache License
@Override public SerializedList<U, T> read(JsonReader jsonReader) throws IOException { ReladomoDeserializer deserializer;/* w ww. java2 s . c om*/ if (this.typeClass == null) { deserializer = new ReladomoDeserializer(); } else { deserializer = new ReladomoDeserializer(typeClass); } deserializer.setIgnoreUnknown(); JsonDeserializerState state = JsonDeserializerState.ListStartState.INSTANCE; while (true) { JsonToken nextToken = jsonReader.peek(); //BEGIN_ARRAY, END_ARRAY, BEGIN_OBJECT, END_OBJECT, NAME, STRING, NUMBER, BOOLEAN, NULL, END_DOCUMENT; if (JsonToken.BEGIN_OBJECT == nextToken) { jsonReader.beginObject(); state = state.startObject(deserializer); } else if (JsonToken.END_OBJECT == nextToken) { jsonReader.endObject(); state = state.endObject(deserializer); } else if (JsonToken.BEGIN_ARRAY == nextToken) { jsonReader.beginArray(); state = state.startArray(deserializer); } else if (JsonToken.END_ARRAY == nextToken) { jsonReader.endArray(); state = state.endArray(deserializer); } else if (JsonToken.BOOLEAN == nextToken) { if (jsonReader.nextBoolean()) { state = state.valueTrue(deserializer); } else { state = state.valueFalse(deserializer); } } else if (JsonToken.NAME == nextToken) { String name = jsonReader.nextName(); state = state.fieldName(name, deserializer); } else if (JsonToken.NUMBER == nextToken) { String value = jsonReader.nextString(); state = state.valueString(value, deserializer); // we do the parsing to avoid precision loss } else if (JsonToken.STRING == nextToken) { String value = jsonReader.nextString(); Attribute attribute = deserializer.getCurrentAttribute(); if (attribute instanceof TimestampAttribute) { Timestamp timestamp = GsonReladomoTypeAdapterSerialWriter.jsonToTimestamp(value); state = state.valueTimestamp(timestamp, deserializer); } else { state = state.valueString(value, deserializer); } } else if (JsonToken.NULL == nextToken) { jsonReader.nextNull(); state = state.valueNull(deserializer); } else if (JsonToken.END_DOCUMENT == nextToken) { break; } } return deserializer.getDeserializedResultAsList(); }
From source file:com.gs.reladomo.serial.gson.GsonWrappedTypedAdapter.java
License:Apache License
@Override public Serialized<T> read(JsonReader jsonReader) throws IOException { ReladomoDeserializer deserializer;// www. j av a 2s . c o m if (this.typeClass == null) { deserializer = new ReladomoDeserializer(); } else { deserializer = new ReladomoDeserializer(typeClass); } deserializer.setIgnoreUnknown(); JsonDeserializerState state = JsonDeserializerState.NormalParserState.INSTANCE; while (true) { JsonToken nextToken = jsonReader.peek(); //BEGIN_ARRAY, END_ARRAY, BEGIN_OBJECT, END_OBJECT, NAME, STRING, NUMBER, BOOLEAN, NULL, END_DOCUMENT; if (JsonToken.BEGIN_OBJECT == nextToken) { jsonReader.beginObject(); state = state.startObject(deserializer); } else if (JsonToken.END_OBJECT == nextToken) { jsonReader.endObject(); state = state.endObject(deserializer); } else if (JsonToken.BEGIN_ARRAY == nextToken) { jsonReader.beginArray(); state = state.startArray(deserializer); } else if (JsonToken.END_ARRAY == nextToken) { jsonReader.endArray(); state = state.endArray(deserializer); } else if (JsonToken.BOOLEAN == nextToken) { if (jsonReader.nextBoolean()) { state = state.valueTrue(deserializer); } else { state = state.valueFalse(deserializer); } } else if (JsonToken.NAME == nextToken) { String name = jsonReader.nextName(); state = state.fieldName(name, deserializer); } else if (JsonToken.NUMBER == nextToken) { String value = jsonReader.nextString(); state = state.valueString(value, deserializer); // we do the parsing to avoid precision loss } else if (JsonToken.STRING == nextToken) { String value = jsonReader.nextString(); Attribute attribute = deserializer.getCurrentAttribute(); if (attribute instanceof TimestampAttribute) { Timestamp timestamp = GsonReladomoTypeAdapterSerialWriter.jsonToTimestamp(value); state = state.valueTimestamp(timestamp, deserializer); } else { state = state.valueString(value, deserializer); } } else if (JsonToken.NULL == nextToken) { jsonReader.nextNull(); state = state.valueNull(deserializer); } else if (JsonToken.END_DOCUMENT == nextToken) { break; } } return deserializer.getDeserializedResult(); }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
License:Open Source License
private TaskData doInBackgroundImportReplace(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace"); Collection col = params[0].getCollection(); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip"; File dir = new File(fileDir); if (dir.exists()) { BackupManager.removeDir(dir);/*from www .j a va 2 s.c o m*/ } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = fileDir + "/collection.anki2"; ZipFile zip; try { zip = new ZipFile(new File(path), ZipFile.OPEN_READ); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); String colPath; if (col != null) { // unload collection and trigger a backup colPath = col.getPath(); AnkiDroidApp.closeCollection(true); BackupManager.performBackup(colPath, true); } // overwrite collection colPath = AnkiDroidApp.getCollectionPath(); File f = new File(colFile); f.renameTo(new File(colPath)); int addedCount = -1; try { col = AnkiDroidApp.openCollection(colPath); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(fileDir, "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().getDir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); publishProgress(new TaskData(res.getString(R.string.import_update_counts))); // Update the counts DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result == null) { return null; } return new TaskData(addedCount, result.getObjArray(), true); } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }
From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java
License:Open Source License
public int run() { publishProgress(false, 0, 0, false); try {//from w w w .j ava2s . c o m // extract the deck from the zip file String tempDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip"; // from anki2.py String colFile = tempDir + "/collection.anki2"; if (!Utils.unzipFiles(mZip, tempDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists() || !Storage.Collection(colFile).validCollection()) { return -2; } // we need the media dict in advance, and we'll need a map of fname number to use during the import File mediaMapFile = new File(tempDir, "media"); HashMap<String, String> numToName = new HashMap<String, String>(); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } _prepareFiles(colFile); publishProgress(true, 0, 0, false); int cnt = -1; try { cnt = _import(); } finally { // do not close collection but close only db (in order not to confuse access counting in storage.java // Note that the media database is still open and needs to be closed below. AnkiDatabaseManager.closeDatabase(mSrc.getPath()); } // import static media String mediaDir = mCol.getMedia().getDir(); if (nameToNum.size() != 0) { for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); if (!file.startsWith("_") && !file.startsWith("latex-")) { continue; } File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(mZip, mediaDir, new String[] { c }, numToName); } } } mZip.close(); mSrc.getMedia().close(); // delete tmp dir File dir = new File(tempDir); BackupManager.removeDir(dir); publishProgress(true, 100, 100, true); return cnt; } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "RuntimeException while importing ", e); return -1; } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "IOException while importing ", e); return -1; } }
From source file:com.ibasco.agql.protocols.valve.dota2.webapi.adapters.Dota2TeamInfoAdapter.java
License:Open Source License
@Override public Dota2MatchTeamInfo read(JsonReader in) throws IOException { in.beginObject();// w w w . j av a 2 s . co m Dota2MatchTeamInfo teamInfo = new Dota2MatchTeamInfo(); while (in.hasNext()) { String name = in.nextName(); if (name.startsWith("league_id_")) { teamInfo.getLeagueIds().add(in.nextInt()); } else if (name.startsWith("player_")) { teamInfo.getPlayerAccountIds().add(in.nextLong()); } else { switch (name) { case "name": teamInfo.setName(in.nextString()); break; case "tag": teamInfo.setTag(in.nextString()); break; case "time_created": teamInfo.setTimeCreated(in.nextLong()); break; case "calibration_games_remaining": teamInfo.setCalibrationGamesRemaining(in.nextInt()); break; case "logo": teamInfo.setLogo(in.nextLong()); break; case "logo_sponsor": teamInfo.setLogoSponsor(in.nextLong()); break; case "country_code": teamInfo.setCountryCode(in.nextString()); break; case "url": teamInfo.setUrl(in.nextString()); break; case "games_played": teamInfo.setGamesPlayed(in.nextInt()); break; case "admin_account_id": teamInfo.setAdminAccountId(in.nextLong()); break; default: break; } } } in.endObject(); return teamInfo; }
From source file:com.ibm.og.json.type.ContainerConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!ContainerConfig.class.equals(rawType)) { return null; }//from w ww . j a v a2 s . com final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override public T read(final JsonReader in) throws IOException { if (JsonToken.STRING == in.peek()) { return (T) new ContainerConfig(in.nextString()); } return delegate.read(in); } }.nullSafe(); }