List of usage examples for com.google.gson.stream JsonReader beginObject
public void beginObject() throws IOException
From source file:org.sprintapi.hyperdata.gson.HyperDataTypeAdapter.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/*from w w w.j av a 2 s .com*/ public Object read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Object instance = constructor.construct(); BoundField metadataField = null; if (metadataAccess != null) { metadataField = boundFields.get(metadataAccess.fieldName); } Object meta = null; Map<String, BoundField> metaBoundFields = null; try { in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if ((name != null) && (metadataField != null) && (name.startsWith(Constants.META_CHAR))) { if (meta == null) { meta = constructorConstructor.get(metadataField.type).construct(); if (!Map.class.isAssignableFrom(meta.getClass())) { metaBoundFields = reflectiveFactory.getBoundFields(gson, metadataField.type, metadataField.type.getRawType()); } } if (metaBoundFields != null) { BoundField field = metaBoundFields.get(name.substring(1)); if (field == null || !field.deserialized) { in.skipValue(); } else { field.read(in, meta); } } else { TypeAdapter<Object> ta = gson.getAdapter(Object.class); Object value = ta.read(in); ((Map) meta).put(name.substring(1), value); } } else if ((name != null) && (!name.equals(metadataAccess.fieldName))) { BoundField field = boundFields.get(name); if (field == null || !field.deserialized) { in.skipValue(); } else { field.read(in, instance); } } } if (metadataAccess.setter != null) { metadataAccess.setter.invoke(instance, meta); //TODO } } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (IllegalArgumentException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { throw new AssertionError(e); } in.endObject(); return instance; }
From source file:org.translator.java.AppInventorProperties.java
License:Apache License
protected AppInventorProperties(JsonReader reader) throws IOException { reader.beginObject(); while (reader.peek() == JsonToken.NAME) { String name = reader.nextName(); if (name.equals("$Components")) { reader.beginArray();/*from w ww .j a v a 2 s .c o m*/ while (reader.peek() == JsonToken.BEGIN_OBJECT) components.add(new AppInventorProperties(reader)); reader.endArray(); } else { String n = reader.nextString(); if (n.matches("True|False")) n = n.toLowerCase(); properties.put(name, n); } } reader.endObject(); }
From source file:org.translator.java.AppInventorScreen.java
License:Apache License
private void parseComponentJSON(JsonReader reader) throws IOException { reader.beginObject(); while (reader.peek() == JsonToken.NAME) { String name = reader.nextName(); if (name.equals("Properties")) form = new AppInventorProperties(reader); else {/*from w w w. j a v a 2 s . co m*/ String d = reader.nextString(); if (d.matches("True|False")) d = d.toLowerCase(); data.put(name, d); } } reader.endObject(); }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
private String readResult(Map<String, String> params, boolean login, boolean retry) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = null; String ret = ""; try {/*from w w w . j a v a 2 s. co m*/ reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (!name.equals("content")) { reader.skipValue(); continue; } JsonToken t = reader.peek(); if (!t.equals(JsonToken.BEGIN_OBJECT)) continue; JsonObject object = new JsonObject(); reader.beginObject(); while (reader.hasNext()) { object.addProperty(reader.nextName(), reader.nextString()); } reader.endObject(); if (object.get(SESSION_ID) != null) { ret = object.get(SESSION_ID).getAsString(); } if (object.get(STATUS) != null) { ret = object.get(STATUS).getAsString(); } if (this.apiLevel == -1 && object.get(API_LEVEL) != null) { this.apiLevel = object.get(API_LEVEL).getAsInt(); } if (object.get(VALUE) != null) { ret = object.get(VALUE).getAsString(); } if (object.get(ERROR) != null) { String message = object.get(ERROR).getAsString(); Context ctx = MyApplication.context(); switch (message) { case API_DISABLED: lastError = ctx.getString(R.string.Error_ApiDisabled, Controller.getInstance().username()); break; case NOT_LOGGED_IN: case LOGIN_ERROR: if (!login && retry && login()) return readResult(params, false, false); // Just do the same request again else lastError = ctx.getString(R.string.Error_LoginFailed); break; case INCORRECT_USAGE: lastError = ctx.getString(R.string.Error_ApiIncorrectUsage); break; case UNKNOWN_METHOD: lastError = ctx.getString(R.string.Error_ApiUnknownMethod); break; default: lastError = ctx.getString(R.string.Error_ApiUnknownError); break; } hasLastError = true; Log.e(TAG, message); return null; } } } finally { if (reader != null) reader.close(); } if (ret.startsWith("\"")) ret = ret.substring(1, ret.length()); if (ret.endsWith("\"")) ret = ret.substring(0, ret.length() - 1); return ret; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
private JsonReader prepareReader(Map<String, String> params, boolean firstCall) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content try {/*from www. ja va 2 s . c o m*/ reader.beginObject(); } catch (Exception e) { e.printStackTrace(); return null; } while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_ARRAY)) { return reader; } else if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); String nextName = reader.nextName(); // We have a BEGIN_OBJECT here but its just the response to call "subscribeToFeed" if ("status".equals(nextName)) return reader; // Handle error while (reader.hasNext()) { if (nextName != null) { object.addProperty(nextName, reader.nextString()); nextName = null; } else { object.addProperty(reader.nextName(), reader.nextString()); } } reader.endObject(); if (object.get(ERROR) != null) { String message = object.get(ERROR).toString(); if (message.contains(NOT_LOGGED_IN)) { lastError = NOT_LOGGED_IN; if (firstCall && login() && !hasLastError) return prepareReader(params, false); // Just do the same request again else return null; } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = MyApplication.context().getString(R.string.Error_ApiDisabled, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = message; } } } else { reader.skipValue(); } } return null; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
private Set<String> parseAttachments(JsonReader reader) throws IOException { Set<String> ret = new HashSet<>(); reader.beginArray();//from w w w. j a v a 2 s. co m while (reader.hasNext()) { String attId = null; String attUrl = null; reader.beginObject(); while (reader.hasNext()) { try { switch (reader.nextName()) { case CONTENT_URL: attUrl = reader.nextString(); break; case ID: attId = reader.nextString(); break; default: reader.skipValue(); break; } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); } } reader.endObject(); if (attId != null && attUrl != null) ret.add(attUrl); } reader.endArray(); return ret; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
/** * parse articles from JSON-reader/*from w ww. ja va 2 s.com*/ * * @param articles container, where parsed articles will be stored * @param reader JSON-reader, containing articles (received from server) * @param skipNames set of names (article properties), which should not be processed (may be {@code null}) * @param filter filter for articles, defining which articles should be omitted while parsing (may be {@code * null}) * @return amount of processed articles */ private int parseArticleArray(final Set<Article> articles, JsonReader reader, Set<Article.ArticleField> skipNames, IArticleOmitter filter) { long time = System.currentTimeMillis(); int count = 0; try { reader.beginArray(); while (reader.hasNext()) { Article article = new Article(); boolean skipObject = false; reader.beginObject(); skipObject = parseArticle(article, reader, skipNames, filter); reader.endObject(); if (!skipObject && article.id != -1 && article.title != null) articles.add(article); count++; } reader.endArray(); } catch (OutOfMemoryError e) { Controller.getInstance().lowMemory(true); // Low memory detected } catch (Exception e) { Log.e(TAG, "Input data could not be read: " + e.getMessage() + " (" + e.getCause() + ")", e); } Log.d(TAG, String.format("parseArticleArray: parsing %s articles took %s ms", count, (System.currentTimeMillis() - time))); return count; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
/** * Retrieves all categories./*from ww w . ja va 2 s .c om*/ * * @return a list of categories. */ public Set<Category> getCategories() { long time = System.currentTimeMillis(); Set<Category> ret = new LinkedHashSet<>(); if (sessionNotAlive()) return ret; Map<String, String> params = new HashMap<>(); params.put(PARAM_OP, VALUE_GET_CATEGORIES); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int id = -1; String title = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { switch (reader.nextName()) { case ID: id = reader.nextInt(); break; case TITLE: title = reader.nextString(); break; case UNREAD: unread = reader.nextInt(); break; default: reader.skipValue(); break; } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); } } reader.endObject(); // Don't handle categories with an id below 1, we already have them in the DB from // Data.updateVirtualCategories() if (id > 0 && title != null) ret.add(new Category(id, title, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { // Empty! } } Log.d(TAG, "getCategories: " + (System.currentTimeMillis() - time) + "ms"); return ret; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
/** * get current feeds from server/*ww w.j a v a 2s.c om*/ * * @param tolerateWrongUnreadInformation if set to {@code false}, then * lazy server will be updated before * @return set of actual feeds on server */ private Set<Feed> getFeeds(boolean tolerateWrongUnreadInformation) { long time = System.currentTimeMillis(); Set<Feed> ret = new LinkedHashSet<>(); if (sessionNotAlive()) return ret; if (!tolerateWrongUnreadInformation) { makeLazyServerWork(); } Map<String, String> params = new HashMap<>(); params.put(PARAM_OP, VALUE_GET_FEEDS); params.put(PARAM_CAT_ID, Data.VCAT_ALL + ""); // Hardcoded -4 fetches all feeds. See // http://tt-rss.org/redmine/wiki/tt-rss/JsonApiReference#getFeeds JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int categoryId = -1; int id = 0; String title = null; String feedUrl = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { switch (reader.nextName()) { case ID: id = reader.nextInt(); break; case CAT_ID: categoryId = reader.nextInt(); break; case TITLE: title = reader.nextString(); break; case FEED_URL: feedUrl = reader.nextString(); break; case UNREAD: unread = reader.nextInt(); break; default: reader.skipValue(); break; } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); } } reader.endObject(); if (id != -1 || categoryId == -2) // normal feed (>0) or label (-2) if (title != null) // Dont like complicated if-statements.. ret.add(new Feed(id, categoryId, title, feedUrl, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { // Empty! } } Log.d(TAG, "getFeeds: " + (System.currentTimeMillis() - time) + "ms"); return ret; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
public SubscriptionResponse feedSubscribe(String feed_url, int category_id) { SubscriptionResponse ret = new SubscriptionResponse(); if (sessionNotAlive()) return ret; Map<String, String> params = new HashMap<>(); params.put(PARAM_OP, VALUE_FEED_SUBSCRIBE); params.put(PARAM_FEED_URL, feed_url); params.put(PARAM_CATEGORY_ID, category_id + ""); String code = ""; String message = null;/*from w w w.j av a 2 s . co m*/ JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "code": code = reader.nextString(); break; case "message": message = reader.nextString(); break; default: reader.skipValue(); break; } } if (!code.contains(UNKNOWN_METHOD)) { ret.code = Integer.parseInt(code); ret.message = message; } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { // Empty! } } return ret; }