@Override public Integer parse(JsonReader reader, float scale) throws IOException { boolean isArray = reader.peek() == JsonToken.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } double r = reader.nextDouble(); double g = reader.nextDouble(); double b = reader.nextDouble(); double a = reader.nextDouble(); if (isArray) { reader.endArray(); } if (r <= 1 && g <= 1 && b <= 1 && a <= 1) { r *= 255; g *= 255; b *= 255; a *= 255; } return Color.argb((int) a, (int) r, (int) g, (int) b); }
@Override public PointF parse(JsonReader reader, float scale) throws IOException { JsonToken token = reader.peek(); if (token == JsonToken.BEGIN_ARRAY) { return JsonUtils.jsonToPoint(reader, scale); } else if (token == JsonToken.BEGIN_OBJECT) { return JsonUtils.jsonToPoint(reader, scale); } else if (token == JsonToken.NUMBER) { // This is the case where the static value for a property is an array of numbers. // We begin the array to see if we have an array of keyframes but it's just an array // of static numbers instead. PointF point = new PointF((float) reader.nextDouble() * scale, (float) reader.nextDouble() * scale); while (reader.hasNext()) { reader.skipValue(); } return point; } else { throw new IllegalArgumentException("Cannot convert json to point. Next token is " + token); } }
static float valueFromObject(JsonReader reader) throws IOException { JsonToken token = reader.peek(); switch (token) { case NUMBER: return (float) reader.nextDouble(); case BEGIN_ARRAY: reader.beginArray(); float val = (float) reader.nextDouble(); while (reader.hasNext()) { reader.skipValue(); } reader.endArray(); return val; default: throw new IllegalArgumentException("Unknown value for token of type " + token); } }
/** Reads the next value in the {@link JsonReader}. */ private static Object readValue(JsonReader reader) throws IOException { JsonToken token = reader.peek(); switch (token) { case BEGIN_OBJECT: return readerToMap(reader); case BEGIN_ARRAY: return readerToList(reader); case BOOLEAN: return reader.nextBoolean(); case NULL: reader.nextNull(); // consume the null token return null; case NUMBER: return reader.nextDouble(); case STRING: return reader.nextString(); default: throw new IllegalStateException("Invalid token " + token); } }
@Override protected Event readNext() throws IOException { if (!reader.hasNext()) { return null; } if (reader.peek() == JsonToken.END_ARRAY) { return null; } try { return parseRecord(); } catch (IOException e) { throw new IOException(getExceptionText(R.string.restore_json_corrupted), e); } }
/** * A generic deserializer for string collections. * * @param serialized JSON representation of a string collection. * @param collectionClass Concrete, instantiatable collection class, e.g. {@code ArrayList.class}. * @param <C> A concrete collection class, e.g. {@code ArrayList<String>}. * @return A collection instance retrieved from {@code serialized}. */ @NonNull public static <C extends Collection<String>> C deserializeStringCollection(@NonNull String serialized, @NonNull Class<?> collectionClass) { C collection = createCollection(collectionClass); StringReader reader = new StringReader(serialized); JsonReader jsonReader = new JsonReader(reader); try { jsonReader.beginArray(); while (jsonReader.hasNext()) { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); collection.add(null); } else { collection.add(jsonReader.nextString()); } } jsonReader.endArray(); jsonReader.close(); return collection; } catch (IOException e) { return collection; } }
private void insertJournal(JsonReader jsonReader, Journal journal) throws IOException { jsonReader.beginObject(); while (jsonReader.hasNext()) { String key = jsonReader.nextName(); if(jsonReader.peek() == JsonToken.NULL) continue; if (key.equals(KEY_ID)) journal.setId(jsonReader.nextLong()); else if (key.equals(KEY_DATE)) journal.setDate(jsonReader.nextLong()); else if (key.equals(KEY_NOTE)) journal.setNote(jsonReader.nextString()); else if (key.equals(KEY_AMOUNT)) journal.setAmount(jsonReader.nextDouble()); else if (key.equals(KEY_CREATED_DATE)) journal.setCreatedDate(jsonReader.nextLong()); else if (key.equals(KEY_TYPE)) journal.setType(Journal.Type.valueOf(jsonReader.nextString())); else if (key.equals(KEY_ATTACHMENTS)) { //this logic assumes that key_attachments comes at the end long newId = mServices.addJournal(journal); insertAttachmentsIntoDB(jsonReader, newId); } else jsonReader.skipValue(); } jsonReader.endObject(); }
private void insertAttachment(JsonReader jsonReader, Attachment attachment) throws IOException { if(jsonReader.peek() == JsonToken.NAME) { jsonReader.beginObject(); while (jsonReader.hasNext()) { String key = jsonReader.nextName(); if (jsonReader.peek() == JsonToken.NULL) continue; if (key.equals(KEY_ID)) attachment.setId(jsonReader.nextLong()); else if (key.equals(KEY_PATH)) attachment.setPath(jsonReader.nextString()); else jsonReader.skipValue(); } mServices.addAttachment(attachment); jsonReader.endObject(); }else{ //for old json format while (jsonReader.hasNext()) { if (jsonReader.peek() == JsonToken.NULL) continue; else attachment.setPath(jsonReader.nextString()); } mServices.addAttachment(attachment); } }
/*** * This method called in the background, here * need to parse given {@code json} * * @param reader Widget configuration */ protected void inflate(ConfigurationWidget widget, JsonReader reader) throws IOException { Bundle options = new Bundle(); Bundle configs = widget.getConfigurations(); JsonToken token = reader.peek(); if(token == JsonToken.BEGIN_OBJECT){ appendViewInLayout(createView(this, configs, options, reader)); }else if (token == JsonToken.BEGIN_ARRAY){ reader.beginArray(); while(reader.peek() != JsonToken.END_ARRAY){ appendViewInLayout(createView(this, configs, options, reader)); options.clear(); // recycle configurations } reader.endArray(); }else{ throw new RuntimeException("Unsupported token exception: " + reader.toString()); } options.clear(); }
private static boolean handleSystemOptions(Bundle options, String key, JsonReader reader){ try { if (key.equals("entities")) { reader.beginObject(); ArrayList<String> entities = new ArrayList<>(); while(reader.peek() != JsonToken.END_OBJECT){ reader.skipValue(); //skip name entities.add(reader.nextString()); } reader.endObject(); options.putStringArrayList(key, entities); return true; } }catch (IOException e){ e.printStackTrace(); } return false; }
/** * Parse the next value as an object, but do not attempt to convert it or any children to a * known type. The returned object will be a {@link JSONObject} and all children will be * JSONObjects, JSONArrays, and primitives. * * @param reader The JsonReader to use. Calls to {@link JsonReader#beginObject()} and {@link * JsonReader#endObject()} will be taken care of by this method. * @param key The key corresponding to the current value. This is used to make more useful error * messages. */ public static JSONObject parseAsJsonObject(JsonReader reader, String key) throws IOException { if (handleNull(reader)) { return null; } assertType(reader, key, JsonToken.BEGIN_OBJECT); JSONObject result = new JSONObject(); reader.beginObject(); while (reader.hasNext()) { try { result.put(reader.nextName(), parseNextValue(reader, false)); } catch (JSONException e) { throw new RuntimeException("This should be impossible.", e); } } reader.endObject(); return result; }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private static void readNGWFeatureAttachments(Feature feature, JsonReader reader) throws IOException { //add extensions reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("attachment") && reader.peek() != JsonToken.NULL) { reader.beginArray(); while (reader.hasNext()) { readNGWFeatureAttachment(feature, reader); } reader.endArray(); } else { reader.skipValue(); } } reader.endObject(); }
@SuppressWarnings("cast") @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static some.test.Simple createUsingJsonStream(Realm realm, JsonReader reader) throws IOException { final some.test.Simple obj = new some.test.Simple(); final SimpleRealmProxyInterface objProxy = (SimpleRealmProxyInterface) obj; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (false) { } else if (name.equals("name")) { if (reader.peek() != JsonToken.NULL) { objProxy.realmSet$name((String) reader.nextString()); } else { reader.skipValue(); objProxy.realmSet$name(null); } } else if (name.equals("age")) { if (reader.peek() != JsonToken.NULL) { objProxy.realmSet$age((int) reader.nextInt()); } else { reader.skipValue(); throw new IllegalArgumentException("Trying to set non-nullable field 'age' to null."); } } else { reader.skipValue(); } } reader.endObject(); return realm.copyToRealm(obj); }
private ParentComment readParentComment() throws IOException { String content = null; String author = null; String link = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); JsonToken check = reader.peek(); if (check == JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "author": author = formatUsername(reader.nextString()); break; case "orig_body": content = reader.nextString().replace("^", ""); break; case "link": link = reader.nextString(); break; default: reader.skipValue(); break; } } reader.endObject(); return new ParentComment(content, author, link); }
public AnnouncementsScraper(Blackboard blackboard) { super(blackboard); handler = new Handler(); runnable = new Runnable() { @Override public void run() { if (!isCancelled()) { getBlackboard().getHtmlContent("announcementList", new ValueCallback<String>() { @Override public void onReceiveValue(String s) { JsonReader reader = new JsonReader(new StringReader(s)); reader.setLenient(true); try { if (reader.peek() != JsonToken.NULL) { if (reader.peek() == JsonToken.STRING) onComplete(reader.nextString()); } } catch (Exception ignored) { } try { reader.close(); } catch (IOException ignored) { } if (!isComplete()) { onError(false); handler.postDelayed(runnable, 1000); } } }); } } }; }
public CourseMenuScraper(Blackboard blackboard) { super(blackboard); handler = new Handler(); runnable = new Runnable() { @Override public void run() { if (!isCancelled()) { getBlackboard().getHtmlContent("courseMenuPalette_contents", new ValueCallback<String>() { @Override public void onReceiveValue(String s) { JsonReader reader = new JsonReader(new StringReader(s)); reader.setLenient(true); try { if (reader.peek() != JsonToken.NULL) { if (reader.peek() == JsonToken.STRING) onComplete(reader.nextString()); } } catch (Exception ignored) { } try { reader.close(); } catch (IOException ignored) { } if (!isComplete()) { onError(false); handler.postDelayed(runnable, 1000); } } }); } } }; }
public UsernameScraper(Blackboard blackboard) { super(blackboard); handler = new Handler(); runnable = new Runnable() { @Override public void run() { if (!isCancelled()) { getBlackboard().getAttribute("global-nav-link", "innerText", new ValueCallback<String>() { @Override public void onReceiveValue(String s) { JsonReader reader = new JsonReader(new StringReader(s)); reader.setLenient(true); try { if (reader.peek() != JsonToken.NULL) { if (reader.peek() == JsonToken.STRING) onComplete(reader.nextString().replace("[0-9]", "")); } } catch (Exception ignored) { } try { reader.close(); } catch (IOException ignored) { } if (!isComplete()) { onError(false); handler.postDelayed(runnable, 1000); } } }); } } }; }
public ContentScraper(Blackboard blackboard) { super(blackboard); handler = new Handler(); runnable = new Runnable() { @Override public void run() { if (!isCancelled()) { getBlackboard().getHtmlContent("content_listContainer", new ValueCallback<String>() { @Override public void onReceiveValue(String s) { JsonReader reader = new JsonReader(new StringReader(s)); reader.setLenient(true); try { if (reader.peek() != JsonToken.NULL) { if (reader.peek() == JsonToken.STRING) onComplete(reader.nextString()); } } catch (Exception ignored) { } try { reader.close(); } catch (IOException ignored) { } if (!isComplete()) { onError(false); handler.postDelayed(runnable, 1000); } } }); } } }; }
@Override public String readString() throws IOException { mReader.nextName(); if (mReader.peek() == JsonToken.NULL) { mReader.nextNull(); return null; } return mReader.nextString(); }
private void readImageUri(JsonReader reader) throws IOException { reader.nextName(); if (reader.peek() == JsonToken.NULL) { reader.nextNull(); mImageUri = null; } else mImageUri = reader.nextString(); }
PodcastLayoutContent parse(Reader reader, URI uri) throws IOException { JsonReader parser = new JsonReader(reader); long id = 0; String name = null; long nextPage = 0; Records records = null; parser.beginObject(); while (parser.hasNext()) { String prop = parser.nextName(); if (ID_PROPERTY.equals(prop)) { id = parser.nextLong(); } else if (TITLE_PROPERTY.equals(prop)) { name = StringUtils.nonEmpty(parser.nextString()); } else if (NEXT_PAGE_PROPERTY.equals(prop)) { if (parser.peek() == JsonToken.NUMBER) { nextPage = parser.nextLong(); } else { parser.skipValue(); } } else if (RECORDS_PROPERTY.equals(prop)) { records = parseRecords(parser, uri); } else { parser.skipValue(); } } parser.endObject(); Podcast podcast = null; if (id != 0 && name != null) { podcast = new Podcast(id, name); } return new PodcastLayoutContent(podcast, records == null ? new Records() : records, nextPage); }
private static void extractSite(final JsonReader reader, final UrlListCallback callback) throws IOException { reader.beginObject(); final String siteOwner = reader.nextName(); { reader.beginObject(); while (reader.hasNext()) { // We can get the site name using reader.nextName() here: reader.skipValue(); JsonToken nextToken = reader.peek(); if (nextToken.name().equals("STRING")) { // Sometimes there's a "dnt" entry, with unspecified purpose. reader.skipValue(); } else { reader.beginArray(); while (reader.hasNext()) { final String blockURL = reader.nextString(); callback.put(blockURL, siteOwner); } reader.endArray(); } } reader.endObject(); } reader.endObject(); }
protected static boolean hasNextSkipNull(JsonReader reader) throws IOException { while (reader.hasNext()) { if (reader.peek() == JsonToken.NULL) { reader.skipValue(); } else { return true; } } return false; }
protected static final String getNextNotNullName(JsonReader reader) throws IOException { while (reader.hasNext()) { String name = reader.nextName(); JsonToken jsonToken = reader.peek(); if (jsonToken != JsonToken.NULL) { return name; } reader.skipValue(); } return null; }
private static ShareTuple decodeTuple(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return ShareTuple.EMPTY_TUPLE; } String workgroup = null; String username = null; String password = null; boolean mounted = true; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { case WORKGROUP_KEY: workgroup = reader.nextString(); break; case USERNAME_KEY: username = reader.nextString(); break; case PASSWORD_KEY: password = reader.nextString(); break; case MOUNT_KEY: mounted = reader.nextBoolean(); default: Log.w(TAG, "Ignoring unknown key " + name); } } reader.endObject(); return new ShareTuple(workgroup, username, password, mounted); }
static <T> List<Keyframe<T>> parse(JsonReader reader, LottieComposition composition, float scale, ValueParser<T> valueParser) throws IOException { List<Keyframe<T>> keyframes = new ArrayList<>(); if (reader.peek() == JsonToken.STRING) { composition.addWarning("Lottie doesn't support expressions."); return keyframes; } reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "k": if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); if (reader.peek() == JsonToken.NUMBER) { // For properties in which the static value is an array of numbers. keyframes.add( KeyframeParser.parse(reader, composition, scale, valueParser, false)); } else { while (reader.hasNext()) { keyframes.add(KeyframeParser.parse(reader, composition, scale, valueParser, true)); } } reader.endArray(); } else { keyframes.add(KeyframeParser.parse(reader, composition, scale, valueParser, false)); } break; default: reader.skipValue(); } } reader.endObject(); setEndFrames(keyframes); return keyframes; }
@Override public ScaleXY parse(JsonReader reader, float scale) throws IOException { boolean isArray = reader.peek() == JsonToken.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } float sx = (float) reader.nextDouble(); float sy = (float) reader.nextDouble(); while (reader.hasNext()) { reader.skipValue(); } if (isArray) { reader.endArray(); } return new ScaleXY(sx / 100f * scale, sy / 100f * scale); }
static PathKeyframe parse( JsonReader reader, LottieComposition composition) throws IOException { boolean animated = reader.peek() == JsonToken.BEGIN_OBJECT; Keyframe<PointF> keyframe = KeyframeParser.parse( reader, composition, Utils.dpScale(), PathParser.INSTANCE, animated); return new PathKeyframe(composition, keyframe); }
static List<PointF> jsonToPoints(JsonReader reader, float scale) throws IOException { List<PointF> points = new ArrayList<>(); reader.beginArray(); while (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); points.add(jsonToPoint(reader, scale)); reader.endArray(); } reader.endArray(); return points; }
private static PointF jsonArrayToPoint(JsonReader reader, float scale) throws IOException { float x; float y; reader.beginArray(); x = (float) reader.nextDouble(); y = (float) reader.nextDouble(); while (reader.peek() != JsonToken.END_ARRAY) { reader.skipValue(); } reader.endArray(); return new PointF(x * scale, y * scale); }
public static AnimatablePathValue parse( JsonReader reader, LottieComposition composition) throws IOException { List<Keyframe<PointF>> keyframes = new ArrayList<>(); if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); while (reader.hasNext()) { keyframes.add(PathKeyframeParser.parse(reader, composition)); } reader.endArray(); KeyframesParser.setEndFrames(keyframes); } else { keyframes.add(new Keyframe<>(JsonUtils.jsonToPoint(reader, Utils.dpScale()))); } return new AnimatablePathValue(keyframes); }
/** * Inserts a Party and it's Journals and attachments into the database * @param jsonReader * @param newParty * @throws IOException */ private void insertParty(JsonReader jsonReader, Party newParty) throws IOException { //consume open curly braces { jsonReader.beginObject(); //loop through keys/names which represents variable while (jsonReader.hasNext()) { String key = jsonReader.nextName(); //if the value is null, continue to next key if (jsonReader.peek() == JsonToken.NULL) continue; if (key.equals(KEY_ID)) newParty.setId(jsonReader.nextLong()); else if (key.equals(KEY_TYPE)) newParty.setType(Party.Type.valueOf(jsonReader.nextString())); else if (key.equals(KEY_NAME)) newParty.setName(jsonReader.nextString()); else if (key.equals(KEY_PHONE)) newParty.setPhone(jsonReader.nextString()); //Debit and Credit balance will be calculated as Journals are added //else if (key.equals(KEY_DEBIT)) newParty.setDebitTotal(jsonReader.nextDouble()); //else if (key.equals(KEY_CREDIT)) newParty.setCreditTotal(jsonReader.nextDouble()); else if (key.equals(KEY_PICTURE)) newParty.setPicturePath(jsonReader.nextString()); else if (key.equals(KEY_JOURNALS)) { //this logic assumes that KEY_JOURNALS comes at the end long id = mServices.addParty(newParty); Log.d(TAG, newParty.getName() + " created"); insertJournalsIntoDb(jsonReader, id); } else jsonReader.skipValue(); //skip unknown key } //consume close curly braces } jsonReader.endObject(); }
static void skipRemainedValues(JsonReader reader, JsonToken endToken) throws IOException{ while (reader.peek() != endToken){ reader.skipValue(); } if(endToken == JsonToken.END_ARRAY){ reader.endArray(); }else { reader.endObject(); } }
public static Bundle asMap(ConfigCard widget, Bundle options, JsonReader reader){ try { reader.beginObject(); while(reader.peek() != JsonToken.END_OBJECT){ final String key = reader.nextName(); if(widget.handleOptions(options, key, reader)){ continue; } final JsonToken token = reader.peek(); if(token == JsonToken.STRING){ options.putString(key, reader.nextString()); }else if(token == JsonToken.BOOLEAN){ options.putBoolean(key, reader.nextBoolean()); }else if(token == JsonToken.NUMBER){ options.putInt(key, reader.nextInt()); }else if(!handleSystemOptions(options, key, reader)){ reader.skipValue(); } } reader.endObject(); } catch (IOException e) { Log.w(TAG, "on >>> " + reader.toString()); e.printStackTrace(); } return options; }
@Test public void testJson2BundleConverter(){ final Activity context = mActivityRule.getActivity(); final ConfigCard widget = new ConfigCard(context); Bundle options = null; try { final JsonReader reader = new JsonReader(new StringReader(getRaw("config_file_sample_base.json"))); //checking only first json object reader.beginObject(); reader.skipValue(); options = ConfigCard.asMap(widget, new Bundle(), reader); JsonMenuInflater.skipRemainedValues(reader, JsonToken.END_OBJECT); reader.close(); }catch (IOException exception){ exception.printStackTrace(); } assertNotNull(options); assertThat(options) .isNotEmpty() .hasSize(3) .hasKey("key") .hasKey("type") .hasKey("entities"); assertEquals("productFlavor", options.getString("key")); assertEquals("spinner", options.getString("type")); ArrayList<String> expected = new ArrayList<>(); expected.add("ProductionMode"); expected.add("DeveloperMode"); assertEquals(expected, options.getStringArrayList("entities")); }
@Test public void testJsonReader() throws IOException{ final Activity context = mActivityRule.getActivity(); final JsonReader reader = new JsonReader(new StringReader( getRaw("config_file_sample_base.json"))); reader.beginObject(); JsonMenuInflater.skipRemainedValues(reader, JsonToken.END_OBJECT); assertEquals(true, reader.peek() == JsonToken.END_DOCUMENT); }