android.util.JsonReader Java Examples

The following examples show how to use android.util.JsonReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AvatarPartDb.java    From cat-avatar-generator-app with Apache License 2.0 6 votes vote down vote up
private void readParts(JsonReader reader) throws IOException {
    reader.beginArray();
    Vector<AvatarPart> parts = null;
    String currentCategory = "";
    while (reader.hasNext()) {
        reader.beginArray();
        String category = reader.nextString();
        if (!category.equals(currentCategory)) {
            parts = new Vector<>();
            mParts.put(category, parts);
            currentCategory = category;
        }
        AvatarPart part = null;
        String filename = reader.nextString();
        int x = reader.nextInt();
        int y = reader.nextInt();
        if (!TextUtils.isEmpty(filename)) {
            part = new AvatarPart(filename, x, y);
        }
        assert parts != null;
        parts.add(part);
        reader.endArray();
    }
    reader.endArray();
}
 
Example #2
Source File: GalleryData.java    From NClientV2 with Apache License 2.0 6 votes vote down vote up
private void parseJSON(JsonReader jr) throws IOException {
    jr.beginObject();
    while(jr.peek()!= JsonToken.END_OBJECT){
        switch(jr.nextName()){
            case "upload_date":uploadDate=new Date(jr.nextLong()*1000);break;
            case "num_favorites":favoriteCount=jr.nextInt();break;
            case "media_id":mediaId=jr.nextInt();break;
            case "title":readTitles(jr);break;
            case "images":readImages(jr); break;
            case "tags":readTags(jr);break;
            case "id":id=jr.nextInt();break;
            case "num_pages":pageCount=jr.nextInt();break;
            case "error":jr.skipValue(); valid=false;break;
            default:jr.skipValue();break;
        }
    }
    jr.endObject();
}
 
Example #3
Source File: AboutJSONParser.java    From pivaa with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Paring object
 * @param reader
 * @return
 * @throws IOException
 */
private AboutRecord readMessage(JsonReader reader) throws IOException {
    String name = "";
    String description = "";

    reader.beginObject();
    while (reader.hasNext()) {
        String key = reader.nextName();

        if (key.equals("name")) {
            name = reader.nextString();

        } else if (key.equals("description")) {
            description = reader.nextString();

        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return new AboutRecord(name, description);
}
 
Example #4
Source File: BundleDeltaClient.java    From react-native-GPay with MIT License 6 votes vote down vote up
private static int patchDelta(JsonReader jsonReader, LinkedHashMap<Number, byte[]> map)
  throws IOException {
  jsonReader.beginArray();

  int numModules = 0;
  while (jsonReader.hasNext()) {
    jsonReader.beginArray();

    int moduleId = jsonReader.nextInt();

    if (jsonReader.peek() == JsonToken.NULL) {
      jsonReader.skipValue();
      map.remove(moduleId);
    } else {
      map.put(moduleId, jsonReader.nextString().getBytes());
    }

    jsonReader.endArray();
    numModules++;
  }

  jsonReader.endArray();

  return numModules;
}
 
Example #5
Source File: LogResponse.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
public static LogResponse fromJson(@NonNull Reader reader) throws IOException {
  JsonReader jsonReader = new JsonReader(reader);
  try {
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
      String name = jsonReader.nextName();
      if (name.equals("nextRequestWaitMillis")) {
        if (jsonReader.peek() == JsonToken.STRING) {
          return LogResponse.create(Long.parseLong(jsonReader.nextString()));
        } else {
          return LogResponse.create(jsonReader.nextLong());
        }
      }
      jsonReader.skipValue();
    }
    throw new IOException("Response is missing nextRequestWaitMillis field.");
  } finally {
    jsonReader.close();
  }
}
 
Example #6
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
private static Event.Log parseEventLog(@NonNull JsonReader jsonReader) throws IOException {
  final Event.Log.Builder builder = Event.Log.builder();

  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    switch (name) {
      case "content":
        builder.setContent(jsonReader.nextString());
        break;
      default:
        jsonReader.skipValue();
        break;
    }
  }
  jsonReader.endObject();
  return builder.build();
}
 
Example #7
Source File: Utility.java    From SoldierWeather with Apache License 2.0 6 votes vote down vote up
/**
 * 解析和处理服务器返回的数据
 * @param soldierWeatherDb
 * @param in
 * @return
 */
public static boolean handleResponse(SoldierWeatherDB soldierWeatherDb, InputStream in) {
    LogUtil.log("Utility", "handleResponse", LogUtil.DEBUG);
    soldierWeatherDB = soldierWeatherDb;
    JsonReader reader = new JsonReader(new InputStreamReader(in));
    boolean flag = false;
    try {
        reader.beginObject();
        while (reader.hasNext()) {
            String nodeName = reader.nextName();
            if (nodeName.equals("resultcode")) {
                LogUtil.log("Utility", "resultcode = " + reader.nextString(), LogUtil.NOTHING);
                flag = true;
            } else if (nodeName.equals("result") && flag) {
                saveAreaToDatabase(reader);
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #8
Source File: AndroidPlacesApiJsonParser.java    From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License 6 votes vote down vote up
List<PlaceType> readPlaceTypesArray(JsonReader reader) throws IOException {
    List<PlaceType> types = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        switch (reader.nextString()) {
            case "route":
                types.add(PlaceType.ROUTE);
                break;
            case "geocode":
                types.add(PlaceType.GEOCODE);
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endArray();
    return types;
}
 
Example #9
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
private static CrashlyticsReport.FilesPayload.File parseFile(@NonNull JsonReader jsonReader)
    throws IOException {
  final CrashlyticsReport.FilesPayload.File.Builder builder =
      CrashlyticsReport.FilesPayload.File.builder();

  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    switch (name) {
      case "filename":
        builder.setFilename(jsonReader.nextString());
        break;
      case "contents":
        builder.setContents(Base64.decode(jsonReader.nextString(), Base64.NO_WRAP));
        break;
      default:
        jsonReader.skipValue();
        break;
    }
  }
  jsonReader.endObject();

  return builder.build();
}
 
Example #10
Source File: FirebaseInstallationServiceClient.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private TokenResult readGenerateAuthTokenResponse(HttpURLConnection conn) throws IOException {
  InputStream inputStream = conn.getInputStream();
  JsonReader reader = new JsonReader(new InputStreamReader(inputStream, UTF_8));
  TokenResult.Builder builder = TokenResult.builder();
  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    if (name.equals("token")) {
      builder.setToken(reader.nextString());
    } else if (name.equals("expiresIn")) {
      builder.setTokenExpirationTimestamp(parseTokenExpirationTimestamp(reader.nextString()));
    } else {
      reader.skipValue();
    }
  }
  reader.endObject();
  reader.close();
  inputStream.close();

  return builder.setResponseCode(TokenResult.ResponseCode.OK).build();
}
 
Example #11
Source File: SampleChooserActivity.java    From ExoPlayer-Offline with Apache License 2.0 6 votes vote down vote up
@Override
protected List<SampleGroup> doInBackground(String... uris) {
  List<SampleGroup> result = new ArrayList<>();
  Context context = getApplicationContext();
  String userAgent = Util.getUserAgent(context, "ExoPlayerDemo");
  DataSource dataSource = new DefaultDataSource(context, null, userAgent, false);
  for (String uri : uris) {
    DataSpec dataSpec = new DataSpec(Uri.parse(uri));
    InputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
    try {
      readSampleGroups(new JsonReader(new InputStreamReader(inputStream, "UTF-8")), result);
    } catch (Exception e) {
      Log.e(TAG, "Error loading sample list: " + uri, e);
      sawError = true;
    } finally {
      Util.closeQuietly(dataSource);
    }
  }
  return result;
}
 
Example #12
Source File: DecisionTree.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
private void readJsonQuestions(final JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext()) {
        final String questionId = reader.nextName();

        final Question question = questionsMap.get(questionId);
        if (question != null) {
            readJsonQuestion(reader, question);
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
}
 
Example #13
Source File: NGWUtil.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void readNGWFeatureAttachment(Feature feature, JsonReader reader)
        throws IOException
{
    reader.beginObject();
    String attachId = "";
    String name = "";
    String mime = "";
    String descriptionText = "";
    while (reader.hasNext()) {
        String keyName = reader.nextName();
        if (reader.peek() == JsonToken.NULL) {
            reader.skipValue();
            continue;
        }

        if (keyName.equals(NGWUtil.NGWKEY_ID)) {
            attachId += reader.nextLong();
        } else if (keyName.equals(NGWUtil.NGWKEY_NAME)) {
            name += reader.nextString();
        } else if (keyName.equals(NGWUtil.NGWKEY_MIME)) {
            mime += reader.nextString();
        } else if (keyName.equals(NGWUtil.NGWKEY_DESCRIPTION)) {
            descriptionText += reader.nextString();
        } else {
            reader.skipValue();
        }
    }
    AttachItem item = new AttachItem(attachId, name, mime, descriptionText);
    feature.addAttachment(item);

    reader.endObject();
}
 
Example #14
Source File: BlocklistProcessor.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
private static void extractCategory(final JsonReader reader, final UrlListCallback callback) throws IOException {
    reader.beginArray();

    while (reader.hasNext()) {
        extractSite(reader, callback);
    }

    reader.endArray();
}
 
Example #15
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Event.Application.Execution.Signal parseEventSignal(@NonNull JsonReader jsonReader)
    throws IOException {
  final Event.Application.Execution.Signal.Builder builder =
      Event.Application.Execution.Signal.builder();

  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    switch (name) {
      case "name":
        builder.setName(jsonReader.nextString());
        break;
      case "code":
        builder.setCode(jsonReader.nextString());
        break;
      case "address":
        builder.setAddress(jsonReader.nextLong());
        break;
      default:
        jsonReader.skipValue();
        break;
    }
  }
  jsonReader.endObject();
  return builder.build();
}
 
Example #16
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Event.Application.Execution.BinaryImage parseEventBinaryImage(
    @NonNull JsonReader jsonReader) throws IOException {
  final Event.Application.Execution.BinaryImage.Builder builder =
      Event.Application.Execution.BinaryImage.builder();

  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    switch (name) {
      case "name":
        builder.setName(jsonReader.nextString());
        break;
      case "baseAddress":
        builder.setBaseAddress(jsonReader.nextLong());
        break;
      case "size":
        builder.setSize(jsonReader.nextLong());
        break;
      case "uuid":
        builder.setUuidFromUtf8Bytes(Base64.decode(jsonReader.nextString(), Base64.NO_WRAP));
        break;
      default:
        jsonReader.skipValue();
        break;
    }
  }
  jsonReader.endObject();
  return builder.build();
}
 
Example #17
Source File: EntityListProcessor.java    From firefox-echo-show with Mozilla Public License 2.0 5 votes vote down vote up
private EntityListProcessor(final JsonReader reader) throws IOException {
    reader.beginObject();

    while (reader.hasNext()) {
        // We can get the siteName using reader.nextName() here
        reader.skipValue();

        handleSite(reader);
    }

    reader.endObject();
}
 
Example #18
Source File: SampleChooserActivity.java    From ExoPlayer-Offline with Apache License 2.0 5 votes vote down vote up
private void readSampleGroup(JsonReader reader, List<SampleGroup> groups) throws IOException {
  String groupName = "";
  ArrayList<Sample> samples = new ArrayList<>();

  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    switch (name) {
      case "name":
        groupName = reader.nextString();
        break;
      case "samples":
        reader.beginArray();
        while (reader.hasNext()) {
          samples.add(readEntry(reader, false));
        }
        reader.endArray();
        break;
      case "offline_samples":
        reader.beginArray();
        while (reader.hasNext()){
          samples.add(readOfflineEntry(reader));
        }
        reader.endArray();
        break;
      case "_comment":
        reader.nextString(); // Ignore.
        break;
      default:
        throw new ParserException("Unsupported name: " + name);
    }
  }
  reader.endObject();

  SampleGroup group = getGroup(groupName, groups);
  group.samples.addAll(samples);
}
 
Example #19
Source File: MetadataParser.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parses metadata in the JSON format.
 * @param input a stream reader expected to contain JSON formatted metadata.
 * @return dictionary metadata, as an array of WordListMetadata objects.
 * @throws IOException if the underlying reader throws IOException during reading.
 * @throws BadFormatException if the data was not in the expected format.
 */
public static List<WordListMetadata> parseMetadata(final InputStreamReader input)
        throws IOException, BadFormatException {
    JsonReader reader = new JsonReader(input);
    final ArrayList<WordListMetadata> readInfo = new ArrayList<>();
    reader.beginArray();
    while (reader.hasNext()) {
        final WordListMetadata thisMetadata = parseOneWordList(reader);
        if (!TextUtils.isEmpty(thisMetadata.mLocale))
            readInfo.add(thisMetadata);
    }
    return Collections.unmodifiableList(readInfo);
}
 
Example #20
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
private static CrashlyticsReport parseReport(@NonNull JsonReader jsonReader) throws IOException {
  final CrashlyticsReport.Builder builder = CrashlyticsReport.builder();

  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    switch (name) {
      case "sdkVersion":
        builder.setSdkVersion(jsonReader.nextString());
        break;
      case "gmpAppId":
        builder.setGmpAppId(jsonReader.nextString());
        break;
      case "platform":
        builder.setPlatform(jsonReader.nextInt());
        break;
      case "installationUuid":
        builder.setInstallationUuid(jsonReader.nextString());
        break;
      case "buildVersion":
        builder.setBuildVersion(jsonReader.nextString());
        break;
      case "displayVersion":
        builder.setDisplayVersion(jsonReader.nextString());
        break;
      case "session":
        builder.setSession(parseSession(jsonReader));
        break;
      case "ndkPayload":
        builder.setNdkPayload(parseNdkPayload(jsonReader));
        break;
      default:
        jsonReader.skipValue();
        break;
    }
  }
  jsonReader.endObject();
  return builder.build();
}
 
Example #21
Source File: MetadataParser.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
/**
 * Parses metadata in the JSON format.
 * @param input a stream reader expected to contain JSON formatted metadata.
 * @return dictionary metadata, as an array of WordListMetadata objects.
 * @throws IOException if the underlying reader throws IOException during reading.
 * @throws BadFormatException if the data was not in the expected format.
 */
public static List<WordListMetadata> parseMetadata(final InputStreamReader input)
        throws IOException, BadFormatException {
    JsonReader reader = new JsonReader(input);
    final ArrayList<WordListMetadata> readInfo = new ArrayList<>();
    reader.beginArray();
    while (reader.hasNext()) {
        final WordListMetadata thisMetadata = parseOneWordList(reader);
        if (!TextUtils.isEmpty(thisMetadata.mLocale))
            readInfo.add(thisMetadata);
    }
    return Collections.unmodifiableList(readInfo);
}
 
Example #22
Source File: CrashlyticsReportJsonTransform.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
public CrashlyticsReport reportFromJson(@NonNull String json) throws IOException {
  try (JsonReader jsonReader = new JsonReader(new StringReader(json))) {
    return parseReport(jsonReader);
  } catch (IllegalStateException e) {
    throw new IOException(e);
  }
}
 
Example #23
Source File: BlocklistProcessor.java    From firefox-echo-show with Mozilla Public License 2.0 5 votes vote down vote up
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();
}
 
Example #24
Source File: JSONParser.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static long readFieldLong(JsonReader reader, boolean fromDouble) throws IOException {
  reader.nextName();
  if (fromDouble) {
    return Double.valueOf(reader.nextDouble() * 1e8).longValue();
  }

  return reader.nextLong();
}
 
Example #25
Source File: JSONParser.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static ZCashTransactionInput readTxSingleInput(JsonReader reader) throws IOException {
  ZCashTransactionInput input = new ZCashTransactionInput();
  reader.beginObject();
  while (reader.peek() != JsonToken.END_OBJECT) {
    String name = reader.nextName();
    switch (name) {
      case COINBASE:
        input.coinbase = reader.nextString();
        break;
      case SEQUENCE:
        input.sequence = reader.nextLong();
        break;
      case TXID:
        input.txid = reader.nextString();
        break;
      case VOUT:
        input.n = reader.nextLong();
        break;
      case SCRIPTSIG:
        reader.skipValue();
        break;
      case RETRIEVEDVOUT:
        input.copyDataFrom(readTxSingleOutput(reader));
        break;
      default:
        reader.skipValue();
    }
  }

  reader.endObject();
  return input;
}
 
Example #26
Source File: JSONParser.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static Vector<ZCashTransactionOutput> readTxInputs(JsonReader reader) throws IOException {
  Vector<ZCashTransactionOutput> vin = new Vector<>();
  reader.beginArray();
  while (reader.hasNext()) {
    vin.add(readTxSingleInput(reader));
  }

  reader.endArray();
  return vin;
}
 
Example #27
Source File: GeoLineString.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setCoordinatesFromJSONStream(JsonReader reader, int crs) throws IOException {
    setCRS(crs);
    reader.beginArray();
    while (reader.hasNext()){
        GeoPoint pt = new GeoPoint();
        pt.setCoordinatesFromJSONStream(reader, crs);
        mPoints.add(pt);
    }
    reader.endArray();
}
 
Example #28
Source File: BatchManagerTest.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchWithNulls() throws JSONException, IOException {

    BackgroundLocation location = new BackgroundLocation();
    location.setBatchStartMillis(1000L);
    location.setStatus(BackgroundLocation.SYNC_PENDING);
    SQLiteLocationDAO dao = new SQLiteLocationDAO(mDbHelper.getWritableDatabase());
    dao.persistLocation(location);

    JSONObject templateJSON = new JSONObject("{\"Nullable\":null, \"NullRadius\": \"@radius\"}");
    LocationTemplate template = LocationTemplateFactory.fromJSON(templateJSON);

    BatchManager batchManager = new BatchManager(mContext);
    File batchFile = batchManager.createBatch(3000L, 0, template);

    HashMap hashLocation = new HashMap<String, Object>();
    JsonReader reader = new JsonReader(new FileReader(batchFile));
    reader.beginArray();
    while (reader.hasNext()) {
        reader.beginObject();
        while(reader.hasNext()) { ;
            hashLocation.put(reader.nextName(), null);
            reader.nextNull();
        }
        reader.endObject();
    }
    reader.endArray();

    Assert.assertTrue(hashLocation.containsKey("Nullable"));
    Assert.assertTrue(hashLocation.containsKey("NullRadius"));
}
 
Example #29
Source File: GeoJSONUtil.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean readGeoJSONCRS(InputStream is, Context context) throws IOException, NGException {
    JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
    boolean isWGS = true;
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if(name.equals(GeoConstants.GEOJSON_CRS)) {
            reader.beginObject();
            while (reader.hasNext()) {
                name = reader.nextName();
                if(name.equals(GeoConstants.GEOJSON_PROPERTIES)) {
                    reader.beginObject();
                    while (reader.hasNext()) {
                        String subname = reader.nextName();
                        if(subname.equals(GeoConstants.GEOJSON_NAME)){
                            String val = reader.nextString();
                            isWGS = checkCRSSupportAndWGS(val, context);
                        }
                        else {
                            reader.skipValue();
                        }
                    }
                    reader.endObject();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    reader.close();
    return isWGS;
}
 
Example #30
Source File: AndroidPlacesApiJsonParser.java    From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License 5 votes vote down vote up
List<String> readTypesArray(JsonReader reader) throws IOException {
    List<String> types = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        types.add(reader.nextString());
    }
    reader.endArray();
    return types;
}