List of usage examples for com.google.gson.stream JsonReader peek
public JsonToken peek() throws IOException
From source file:org.sprintapi.hyperdata.gson.HyperDataTypeAdapter.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from www .j a v a 2s . co m 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.syphr.lametrictime.api.common.impl.typeadapters.imported.RuntimeTypeAdapterFactory.java
License:Apache License
/** * Takes a reader in any state and returns the next value as a JsonElement. *//*from ww w . jav a 2s. c om*/ private static JsonElement parse(JsonReader reader) throws JsonParseException { boolean isEmpty = true; try { reader.peek(); isEmpty = false; return RuntimeTypeAdapterFactory.JSON_ELEMENT.read(reader); } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return a JsonNull for * empty documents instead of throwing. */ if (isEmpty) { return JsonNull.INSTANCE; } // The stream ended prematurely so it is likely a syntax error. throw new JsonSyntaxException(e); } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } }
From source file:org.terasology.utilities.gson.CaseInsensitiveEnumTypeAdapterFactory.java
License:Apache License
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; }//from w w w .j av a2 s .co m final Map<String, T> lowercaseToConstant = Maps.newHashMap(); for (T constant : rawType.getEnumConstants()) { String lowercase = toLowercase(constant); lowercaseToConstant.put(lowercase, constant); } return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(toLowercase(value)); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String value = reader.nextString(); return lowercaseToConstant.get(toLowercase(value)); } } }; }
From source file:org.terasology.utilities.gson.UriTypeAdapterFactory.java
License:Apache License
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!Uri.class.isAssignableFrom(rawType)) { return null; }/*from w ww . j a v a2 s . c o m*/ final Constructor<T> constructor; try { constructor = rawType.getConstructor(String.class); constructor.setAccessible(true); } catch (NoSuchMethodException e) { logger.error("URI type {} lacks String constructor", rawType); return null; } return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value(value.toString()); } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String nextString = reader.nextString(); try { return constructor.newInstance(nextString); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { logger.error("Failed to instantiate uri of type {} from value {}", rawType, nextString, e); return null; } } } }; }
From source file:org.translator.java.AppInventorProperties.java
License:Apache License
protected AppInventorProperties(JsonReader reader) throws IOException { reader.beginObject();// w w w. j a v a2 s . co m while (reader.peek() == JsonToken.NAME) { String name = reader.nextName(); if (name.equals("$Components")) { reader.beginArray(); 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();/* ww w. ja v a 2 s . com*/ while (reader.peek() == JsonToken.NAME) { String name = reader.nextName(); if (name.equals("Properties")) form = new AppInventorProperties(reader); else { 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 {/* w w w . j a v a2 s .c o 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 {// w w w . j a v a2 s .c om 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 boolean parseArticle(final Article a, final JsonReader reader, final Set<Article.ArticleField> skipNames, final IArticleOmitter filter) throws IOException { boolean skipObject = false; while (reader.hasNext() && reader.peek().equals(JsonToken.NAME)) { if (skipObject) { // field name reader.skipValue();/* w w w . j av a2 s.c om*/ // field value reader.skipValue(); continue; } String name = reader.nextName(); Article.ArticleField field = Article.ArticleField.valueOf(name); try { if (skipNames != null && skipNames.contains(field)) { reader.skipValue(); continue; } switch (field) { case id: a.id = reader.nextInt(); break; case title: a.title = reader.nextString(); break; case unread: a.isUnread = reader.nextBoolean(); break; case updated: a.updated = new Date(reader.nextLong() * 1000); break; case feed_id: if (reader.peek() == JsonToken.NULL) reader.nextNull(); else a.feedId = reader.nextInt(); break; case content: a.content = reader.nextString(); break; case link: a.url = reader.nextString(); break; case comments: a.commentUrl = reader.nextString(); break; case attachments: a.attachments = parseAttachments(reader); break; case marked: a.isStarred = reader.nextBoolean(); break; case published: a.isPublished = reader.nextBoolean(); break; case labels: a.labels = parseLabels(reader); break; case author: a.author = reader.nextString(); break; default: reader.skipValue(); continue; } if (filter != null) skipObject = filter.omitArticle(field, a); } catch (IllegalArgumentException | StopJsonParsingException | IOException e) { Log.w(TAG, "Result contained illegal value for entry \"" + field + "\"."); reader.skipValue(); } } return skipObject; }
From source file:org.ttrssreader.net.JSONConnector.java
License:Open Source License
private Set<Label> parseLabels(final JsonReader reader) throws IOException { Set<Label> ret = new HashSet<>(); if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) { reader.beginArray();/* w ww . j a v a 2 s . c om*/ } else { reader.skipValue(); return ret; } try { while (reader.hasNext()) { Label label = new Label(); reader.beginArray(); try { label.id = Integer.parseInt(reader.nextString()); label.caption = reader.nextString(); label.foregroundColor = reader.nextString(); label.backgroundColor = reader.nextString(); label.checked = true; } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } ret.add(label); reader.endArray(); } reader.endArray(); } catch (Exception e) { // Ignore exceptions here try { if (reader.peek().equals(JsonToken.END_ARRAY)) reader.endArray(); } catch (Exception ee) { // Empty! } } return ret; }