Java Code Examples for android.util.JsonReader

The following examples show how to use android.util.JsonReader. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: NClientV2   Source File: GalleryData.java    License: 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 2
Source Project: cat-avatar-generator-app   Source File: AvatarPartDb.java    License: 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 3
Source Project: ExoPlayer-Offline   Source File: SampleChooserActivity.java    License: 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 4
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 5
@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 6
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 7
Source Project: SoldierWeather   Source File: Utility.java    License: 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
@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 9
Source Project: firebase-android-sdk   Source File: LogResponse.java    License: 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 10
Source Project: pivaa   Source File: AboutJSONParser.java    License: 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 11
Source Project: react-native-GPay   Source File: BundleDeltaClient.java    License: 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 12
Source Project: ExoPlayer-Offline   Source File: SampleChooserActivity.java    License: 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 13
@NonNull
private static List<Sticker> readStickers(@NonNull JsonReader reader) throws IOException, IllegalStateException {
    reader.beginArray();
    List<Sticker> stickerList = new ArrayList<>();

    while (reader.hasNext()) {
        reader.beginObject();
        String imageFile = null;
        List<String> emojis = new ArrayList<>(LIMIT_EMOJI_COUNT);
        while (reader.hasNext()) {
            final String key = reader.nextName();
            if ("image_file".equals(key)) {
                imageFile = reader.nextString();
            } else if ("emojis".equals(key)) {
                reader.beginArray();
                while (reader.hasNext()) {
                    String emoji = reader.nextString();
                    emojis.add(emoji);
                }
                reader.endArray();
            } else {
                throw new IllegalStateException("unknown field in json: " + key);
            }
        }
        reader.endObject();
        if (TextUtils.isEmpty(imageFile)) {
            throw new IllegalStateException("sticker image_file cannot be empty");
        }
        if (!imageFile.endsWith(".webp")) {
            throw new IllegalStateException("image file for stickers should be webp files, image file is: " + imageFile);
        }
        if (imageFile.contains("..") || imageFile.contains("/")) {
            throw new IllegalStateException("the file name should not contain .. or / to prevent directory traversal, image file is:" + imageFile);
        }
        stickerList.add(new Sticker(imageFile, emojis));
    }
    reader.endArray();
    return stickerList;
}
 
Example 14
Source Project: openboard   Source File: JsonUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static List<Object> jsonStrToList(final String s) {
    final ArrayList<Object> list = new ArrayList<>();
    final JsonReader reader = new JsonReader(new StringReader(s));
    try {
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            while (reader.hasNext()) {
                final String name = reader.nextName();
                if (name.equals(INTEGER_CLASS_NAME)) {
                    list.add(reader.nextInt());
                } else if (name.equals(STRING_CLASS_NAME)) {
                    list.add(reader.nextString());
                } else {
                    Log.w(TAG, "Invalid name: " + name);
                    reader.skipValue();
                }
            }
            reader.endObject();
        }
        reader.endArray();
        return list;
    } catch (final IOException e) {
    } finally {
        close(reader);
    }
    return Collections.emptyList();
}
 
Example 15
Source Project: Android-Keyboard   Source File: MetadataParser.java    License: 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 16
Source Project: NClientV2   Source File: LoadTags.java    License: Apache License 2.0 5 votes vote down vote up
private void readTags(JsonReader reader) throws IOException{
    reader.beginArray();
    while (reader.hasNext()) {
        Tag tt = new Tag(reader);
        if (tt.getType() != TagType.LANGUAGE && tt.getType() != TagType.CATEGORY) {
            Login.addOnlineTag(tt);
            if (adapter != null) adapter.addItem();
        }
    }
}
 
Example 17
List<AddressComponent> readAddressComponentsArray(JsonReader reader) throws IOException {
    List<AddressComponent> addressComponents = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        String longName = null;
        String shortName = null;
        List<AddressComponentType> types = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "long_name":
                    longName = reader.nextString();
                    break;
                case "short_name":
                    shortName = reader.nextString();
                    break;
                case "types":
                    types = readAddressComponentTypesArray(reader);
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        addressComponents.add(new AddressComponent(longName, shortName, types));
    }
    reader.endArray();
    return addressComponents;
}
 
Example 18
List<AlternativePlaceId> readAltIdsArray(JsonReader reader) throws IOException {
    List<AlternativePlaceId> altIds = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        String placeId = null;
        PlaceScope scope = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "place_id":
                    placeId = reader.nextString();
                    break;
                case "scope":
                    scope = readScope(reader);
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        altIds.add(new AlternativePlaceId(placeId, scope));
    }
    reader.endArray();
    return altIds;
}
 
Example 19
Source Project: NClientV2   Source File: Comment.java    License: Apache License 2.0 5 votes vote down vote up
public Comment(JsonReader reader) throws IOException {
    reader.beginObject();
    while(reader.peek()!= JsonToken.END_OBJECT){
        switch (reader.nextName()){
            case "id":id=reader.nextInt();break;
            case "post_date":postDate=new Date(reader.nextLong()*1000);break;
            case "body":body=reader.nextString();break;
            case "poster":poster=new User(reader);break;
            default:reader.skipValue();break;
        }
    }
    reader.endObject();
}
 
Example 20
Source Project: NClientV2   Source File: Page.java    License: Apache License 2.0 5 votes vote down vote up
public Page(ImageType type, JsonReader reader,int page)throws IOException{
    this.imageType=type;
    this.page=page;
    reader.beginObject();
    while (reader.peek()!= JsonToken.END_OBJECT){
        switch (reader.nextName()){
            case "t":imageExt=stringToExt(reader.nextString()); break;
            case "w":size.setWidth(reader.nextInt());  break;
            case "h":size.setHeight(reader.nextInt()); break;
            default:reader.skipValue();break;
        }
    }
    reader.endObject();
}
 
Example 21
List<OpenPeriod> readOpenPeriodsArray(JsonReader reader) throws IOException {
    List<OpenPeriod> periods = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        DateTimePair open = null;
        DateTimePair close = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "open":
                    open = readDateTimePair(reader);
                    break;
                case "close":
                    close = readDateTimePair(reader);
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        periods.add(new OpenPeriod(open, close));
    }
    reader.endArray();
    return periods;
}
 
Example 22
List<PlacePhoto> readPhotosArray(JsonReader reader) throws IOException {
    List<PlacePhoto> photos = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        int height = -1;
        int width = -1;
        String photoReference = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "height":
                    height = reader.nextInt();
                    break;
                case "width":
                    width = reader.nextInt();
                    break;
                case "photo_reference":
                    photoReference = reader.nextString();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        photos.add(new PlacePhoto(height, width, photoReference));
    }
    reader.endArray();
    return photos;
}
 
Example 23
Source Project: android-test   Source File: ModelCodec.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Object> decodeArray(JsonReader reader) throws IOException {
  List<Object> array = Lists.newArrayList();
  reader.beginArray();
  while (reader.hasNext()) {
    switch (reader.peek()) {
      case BEGIN_OBJECT:
        array.add(decodeObject(reader));
        break;
      case NULL:
        reader.nextNull();
        array.add(null);
        break;
      case STRING:
        array.add(reader.nextString());
        break;
      case BOOLEAN:
        array.add(reader.nextBoolean());
        break;
      case BEGIN_ARRAY:
        array.add(decodeArray(reader));
        break;
      case NUMBER:
        array.add(decodeNumber(reader.nextString()));
        break;
      default:
        throw new IllegalStateException(String.format("%s: bogus token", reader.peek()));
    }
  }

  reader.endArray();
  return array;
}
 
Example 24
Source Project: ExoPlayer-Offline   Source File: SampleChooserActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void readSampleGroups(JsonReader reader, List<SampleGroup> groups) throws IOException {
  reader.beginArray();
  while (reader.hasNext()) {
    readSampleGroup(reader, groups);
  }
  reader.endArray();
}
 
Example 25
Source Project: Wrox-ProfessionalAndroid-4E   Source File: MyViewModel.java    License: Apache License 2.0 5 votes vote down vote up
public Earthquake readEarthquake(JsonReader reader) throws IOException {
  String id = null;
  Location location = null;
  Earthquake earthquakeProperties = null;

  reader.beginObject();

  while (reader.hasNext()) {
    String name = reader.nextName();

    if (name.equals("id")) {
      // The ID is stored as a value.
      id = reader.nextString();
    } else if (name.equals("geometry")) {
      // The location is stored as a geometry object
      // that must be parsed.
      location = readLocation(reader);
    } else if (name.equals("properties")) {
      // Most of the earthquake details are stored as a
      // properties object that must be parsed.
      earthquakeProperties = readEarthquakeProperties(reader);
    } else {
      reader.skipValue();
    }
  }

  reader.endObject();

  // Construct a new Earthquake based on the parsed details.
  return new Earthquake(id,
    earthquakeProperties.getDate(),
    earthquakeProperties.getDetails(),
    location,
    earthquakeProperties.getMagnitude(),
    earthquakeProperties.getLink());
}
 
Example 26
List<Place> readPredictionsArray(JsonReader reader) throws IOException {
    List<Place> predictions = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        predictions.add(readPlace(reader));
    }
    reader.endArray();
    return predictions;
}
 
Example 27
public static List<ZCashTransactionDetails_taddr> parseTxArray(InputStream is) throws IOException {
  JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
  List<ZCashTransactionDetails_taddr> txs = null;
  try {
    txs = readTxArray(reader);
    reader.close();
  } catch (IOException e) {
    e.printStackTrace();
    Log.e("Error message", e.getMessage());
  }

  return txs;
}
 
Example 28
private static List<ZCashTransactionDetails_taddr> readTxArray(JsonReader reader) throws IOException {
  List<ZCashTransactionDetails_taddr> txs = new LinkedList<>();
  reader.beginArray();
  while (reader.hasNext()) {
    txs.add(readTx(reader));
  }

  reader.endArray();
  return txs;
}
 
Example 29
Source Project: focus-android   Source File: EntityListProcessor.java    License: 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 30
List<RatingAspect> readAspectsArray(JsonReader reader) throws IOException {
    List<RatingAspect> aspects = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        int rating = -1;
        String type = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "rating":
                    rating = reader.nextInt();
                    break;
                case "type":
                    type = reader.nextString();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        aspects.add(new RatingAspect(rating, type));
    }
    reader.endArray();
    return aspects;
}