Java Code Examples for android.util.JsonReader.nextName()

The following are Jave code examples for showing how to use nextName() of the android.util.JsonReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: nifi-android-s2s   File: Port.java   Source Code and License Vote up 6 votes
public Port(JsonReader jsonReader) throws IOException {
    jsonReader.beginObject();
    String id = null;
    String name = null;
    while (jsonReader.hasNext()) {
        String key = jsonReader.nextName();
        if (id == null && ID.equals(key)) {
            id = jsonReader.nextString();
        } else if (name == null && NAME.equals(key)) {
            name = jsonReader.nextString();
        } else {
            jsonReader.skipValue();
        }
    }
    jsonReader.endObject();
    this.id = id;
    this.name = name;
}
 
Example 2
Project: BTNotifierAndroid   File: IncomingMessage.java   Source Code and License Vote up 6 votes
public IncomingMessage(String message) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(message));
    reader.beginObject();
    if (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("event")) {
            String typeString = reader.nextString();
            if (typeString.equals("action")) {
                eventType = EventType.ACTION;
            } else if (typeString.equals("dismiss")) {
                eventType = EventType.DISMISS;
            } else if (typeString.equals("blacklist")) {
                eventType = EventType.BLACKLIST;
            } else if (typeString.equals("sms")) {
                eventType = EventType.SMS;
            }
        }
    }
    jsonReader = reader;
}
 
Example 3
Project: pivaa   File: AboutJSONParser.java   Source Code and License Vote up 6 votes
/**
 * 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
Project: firefox-tv   File: BlocklistProcessor.java   Source Code and License Vote up 6 votes
public static Map<String, Trie> loadCategoryMap(final JsonReader reader, final Map<String, Trie> categoryMap, final ListType listType) throws IOException {
    reader.beginObject();

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

        if (name.equals("categories")) {
            extractCategories(reader, categoryMap, listType);
        } else {
            reader.skipValue();
        }
    }

    reader.endObject();

    return categoryMap;
}
 
Example 5
Project: memoria-politica   File: CandidateDao.java   Source Code and License Vote up 6 votes
private List<Politician> findCandidates(List<String> cpfList, JsonReader reader) throws IOException {
    reader.beginArray();

    List<Politician> candidates = new ArrayList<>();
    while (reader.hasNext()) {
        reader.beginObject();
        String polCpf = reader.nextName();
        int index = cpfList.indexOf(polCpf);
        if (index != -1) {
            Politician pol = new Politician(polCpf);
            readJsonObject(reader, pol);
            candidates.add(pol);
        }
        else {
            reader.skipValue();
        }
        reader.endObject();
    }

    reader.endArray();
    return candidates;
}
 
Example 6
Project: cosi   File: FileUtils.java   Source Code and License Vote up 6 votes
private static JSONObject readRootObject(JsonReader reader, boolean isFolder) throws IOException, JSONException {
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();

        if (name.equals("value")) {
            JSONObject result = FileUtils.readObject(reader, isFolder);
            reader.endObject();
            return result;
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();

    return null;
}
 
Example 7
Project: lottie-android   File: JsonUtils.java   Source Code and License Vote up 6 votes
private static PointF jsonObjectToPoint(JsonReader reader, float scale) throws IOException {
  float x = 0f;
  float y = 0f;
  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "x":
        x = valueFromObject(reader);
        break;
      case "y":
        y = valueFromObject(reader);
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();
  return new PointF(x * scale, y * scale);
}
 
Example 8
Project: lottie-android   File: AnimatableTextPropertiesParser.java   Source Code and License Vote up 6 votes
public static AnimatableTextProperties parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  AnimatableTextProperties anim = null;

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "a":
        anim = parseAnimatableTextProperties(reader, composition);
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();
  if (anim == null) {
    // Not sure if this is possible.
    return new AnimatableTextProperties(null, null, null, null);
  }
  return anim;
}
 
Example 9
Project: lottie-android   File: ShapePathParser.java   Source Code and License Vote up 6 votes
static ShapePath parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  String name = null;
  int ind = 0;
  AnimatableShapeValue shape = null;

  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "nm":
        name = reader.nextString();
        break;
      case "ind":
        ind = reader.nextInt();
        break;
      case "ks":
        shape = AnimatableValueParser.parseShapeData(reader, composition);
        break;
      default:
        reader.skipValue();
    }
  }

  return new ShapePath(name, ind, shape);
}
 
Example 10
Project: dailyJournal   File: JsonConverterStream.java   Source Code and License Vote up 6 votes
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();
}
 
Example 11
Project: samples-android   File: RegistrationApiResponse.java   Source Code and License Vote up 6 votes
private RegistrationApiResponse readMessage(JsonReader reader) throws IOException {
    boolean isRegistered = false;
    Warranty warranty = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("IsRegistered")) {
            isRegistered = reader.nextBoolean();
        } else if (name.equals("Warranty")) {
            warranty = readWarranty(reader);
        } else {
            reader.skipValue();
        }
    }
    return new RegistrationApiResponse(isRegistered, warranty);
}
 
Example 12
Project: SMSGateway   File: JSONParser.java   Source Code and License Vote up 6 votes
public SMSMessage parse() throws IOException {
    JsonReader jsonReader = new JsonReader(new StringReader(jsonString));

    String recipient = null;
    String message = null;

    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
        String attributeName = jsonReader.nextName();
        if (attributeName.equals("sender_recipient")) {
            recipient = jsonReader.nextString();
        } else if (attributeName.equals("text")) {
            message = jsonReader.nextString();
        } else {
            jsonReader.skipValue();
        }
    }
    jsonReader.endObject();

    return new SMSMessage(recipient, message);
}
 
Example 13
Project: nexus-gallery   File: FilterColorBorderRepresentation.java   Source Code and License Vote up 6 votes
public void deSerializeRepresentation(JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equalsIgnoreCase("size")) {
            mParamSize.setValue(reader.nextInt());
        } else if (name.equalsIgnoreCase("radius")) {
            mParamRadius.setValue(reader.nextInt());
        } else if (name.equalsIgnoreCase("color")) {
            mParamColor.setValue(reader.nextInt());
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
}
 
Example 14
Project: CatSaver   File: ReleaseInfo.java   Source Code and License Vote up 6 votes
public final void initialize(final JsonReader reader) throws IOException, ParseException {
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            default:
                reader.skipValue();
                break;
            case "tag_name":
                version = reader.nextString().substring(1);
                break;
            case "published_at":
                date = ISO8601.parse(reader.nextString());
                break;
            case "assets":
                initializeAssets(reader);
                break;
            case "body":
                info = reader.nextString();
                break;
        }
    }
    reader.endObject();
}
 
Example 15
Project: csci578   File: Utilities.java   Source Code and License Vote up 6 votes
/**
 * Reads a result from a JsonReader. Closes the reader.
 *
 * @param reader the reader from which to read the result
 * @return the result
 * @throws IOException if there is an exception in the reader
 */
public static Result getResult(JsonReader reader) throws IOException {

    reader.beginObject();

    Result result = new Result();

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

        if("code".equals(name)) {
            result.setCode(reader.nextInt());
        } else if("message".equals(name)) {
            result.setMessage(reader.nextString());
        }
    }

    reader.endObject();
    reader.close();

    return result;
}
 
Example 16
Project: nexus-gallery   File: FilterCropRepresentation.java   Source Code and License Vote up 6 votes
@Override
public void deSerializeRepresentation(JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (BOUNDS[0].equals(name)) {
            mCrop.left = (float) reader.nextDouble();
        } else if (BOUNDS[1].equals(name)) {
            mCrop.top = (float) reader.nextDouble();
        } else if (BOUNDS[2].equals(name)) {
            mCrop.right = (float) reader.nextDouble();
        } else if (BOUNDS[3].equals(name)) {
            mCrop.bottom = (float) reader.nextDouble();
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
}
 
Example 17
Project: samples-android   File: RegistrationApiResponse.java   Source Code and License Vote up 6 votes
private Warranty readWarranty(JsonReader reader) throws IOException {
    Boolean extensionEligible = false;
    String description = null;
    String expiration = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("ExtensionEligible")) {
            extensionEligible = reader.nextBoolean();
        } else if (name.equals("Description")) {
            description = reader.nextString();
        } else if (name.equals("EndDate")) {
            expiration = reader.nextString();
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();

    return new Warranty(extensionEligible, description, expiration);
}
 
Example 18
Project: nexus-gallery   File: FilterMirrorRepresentation.java   Source Code and License Vote up 6 votes
@Override
public void deSerializeRepresentation(JsonReader reader) throws IOException {
    boolean unset = true;
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (SERIALIZATION_MIRROR_VALUE.equals(name)) {
            Mirror r = Mirror.fromValue((char) reader.nextInt());
            if (r != null) {
                setMirror(r);
                unset = false;
            }
        } else {
            reader.skipValue();
        }
    }
    if (unset) {
        Log.w(TAG, "WARNING: bad value when deserializing " + SERIALIZATION_NAME);
    }
    reader.endObject();
}
 
Example 19
Project: android-PlacesAutocompleteTextView   File: AndroidPlacesApiJsonParser.java   Source Code and License Vote up 6 votes
PlaceGeometry readGeometry(JsonReader reader) throws IOException {
    double lat = -1.0;
    double lng = -1.0;

    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "lat":
                lat = reader.nextDouble();
                break;
            case "lng":
                lng = reader.nextDouble();
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return new PlaceGeometry(new PlaceLocation(lat, lng));
}
 
Example 20
Project: webtrekk-android-sdk   File: WebtrekkRecommendations.java   Source Code and License Vote up 5 votes
private void processResponseRecoItem(JsonReader reader, List<RecommendationProduct> recommendations) throws IOException {

            String title = null, id = null;
            Map<String, RecommendationProductValue> recommendationValues = new HashMap<>();

            reader.beginArray();//begin array of one recommendation
            while (reader.hasNext())
            {

                String value = null, identifier = null, type = null;

                reader.beginObject(); //read recommendation item
                while (reader.hasNext()) {
                    String name = reader.nextName();
                    if (name.equals("value"))
                        value = reader.nextString();
                    else if (name.equals("identifier"))
                        identifier = reader.nextString();
                    else if (name.equals("type"))
                        type = reader.nextString();
                    else
                        reader.skipValue();
                }
                reader.endObject();

                if (identifier.equals("id"))
                    id = value;
                else if(identifier.equals("campaignTitle"))
                    title = value;
                else
                   recommendationValues.put(identifier, new RecommendationProductValue(type, value));
            }
            reader.endArray();
            if (id != null)
                recommendations.add(new RecommendationProduct(id, title, recommendationValues));
            else
            {
                WebtrekkLogging.log("Incorrect recommendation. Lack of id. Title:"+title);
            }
        }
 
Example 21
Project: Smarty-Streets-AutoCompleteTextView   File: AndroidSmartyStreetsApiJsonParser.java   Source Code and License Vote up 5 votes
Address readPlace(JsonReader reader) throws IOException {
    String text = null;
    String streetLine = null;
    String city = null;
    String state = null;
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "text":
                text = reader.nextString();
                break;
            case "street_line":
                streetLine = reader.nextString();
                break;
            case "city":
                city = reader.nextString();
                break;
            case "state":
                state = reader.nextString();
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return new Address(text, streetLine, city, state);
}
 
Example 22
Project: nifi-android-s2s   File: TransactionResultParser.java   Source Code and License Vote up 5 votes
public static TransactionResult parseTransactionResult(InputStream inputStream) throws IOException {
    int flowFilesSent = 0;
    int responseCode = -1;
    String message = null;
    JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
    try {
        jsonReader.beginObject();
        try {
            while (jsonReader.hasNext()) {
                String nextName = jsonReader.nextName();
                if (FLOW_FILE_SENT.equals(nextName)) {
                    flowFilesSent = jsonReader.nextInt();
                } else if (RESPONSE_CODE.equals(nextName)) {
                    responseCode = jsonReader.nextInt();
                } else if (MESSAGE.equals(nextName)) {
                    message = jsonReader.nextString();
                } else {
                    jsonReader.skipValue();
                }
            }
        } finally {
            jsonReader.endObject();
        }
    } finally {
        jsonReader.close();
    }
    return new TransactionResult(flowFilesSent, responseCode == -1 ? null : ResponseCode.fromCode(responseCode), message);
}
 
Example 23
Project: nifi-android-s2s   File: SiteToSiteInfo.java   Source Code and License Vote up 5 votes
public SiteToSiteInfo(InputStream inputStream) throws IOException {
    List<Port> inputPorts = new ArrayList<>();
    Integer rawSiteToSitePort = null;
    JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
    try {
        jsonReader.beginObject();
        while (jsonReader.hasNext()) {
            if (CONTROLLER.equals(jsonReader.nextName())) {
                jsonReader.beginObject();
                while (jsonReader.hasNext()) {
                    String controllerKey = jsonReader.nextName();
                    if (INPUT_PORTS.equals(controllerKey)) {
                        inputPorts = Port.parsePortArray(jsonReader);
                    } else if (REMOTE_SITE_LISTENING_PORT.equals(controllerKey)) {
                        try {
                            rawSiteToSitePort = jsonReader.nextInt();
                        } catch (Exception e) {
                            rawSiteToSitePort = null;
                        }
                    } else {
                        jsonReader.skipValue();
                    }
                }
                jsonReader.endObject();
            } else {
                jsonReader.skipValue();
            }
        }
        jsonReader.endObject();
    } finally {
        jsonReader.close();
    }
    this.rawSiteToSitePort = rawSiteToSitePort;
    this.inputPorts = inputPorts;
}
 
Example 24
Project: samba-documents-provider   File: ShareManager.java   Source Code and License Vote up 5 votes
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);
}
 
Example 25
Project: lighthouse   File: PodcastJsonParser.java   Source Code and License Vote up 5 votes
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);
}
 
Example 26
Project: firefox-tv   File: BlocklistProcessor.java   Source Code and License Vote up 5 votes
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 27
Project: lottie-android   File: RectangleShapeParser.java   Source Code and License Vote up 5 votes
static RectangleShape parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  String name = null;
  AnimatableValue<PointF, PointF> position = null;
  AnimatablePointValue size = null;
  AnimatableFloatValue roundedness = null;

  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "nm":
        name = reader.nextString();
        break;
      case "p":
        position =
            AnimatablePathValueParser.parseSplitPath(reader, composition);
        break;
      case "s":
        size = AnimatableValueParser.parsePoint(reader, composition);
        break;
      case "r":
        roundedness = AnimatableValueParser.parseFloat(reader, composition);
        break;
      default:
        reader.skipValue();
    }
  }

  return new RectangleShape(name, position, size, roundedness);
}
 
Example 28
Project: focus-android   File: BlocklistProcessor.java   Source Code and License Vote up 5 votes
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 29
Project: memoria-politica   File: CandidateDao.java   Source Code and License Vote up 5 votes
private Politician readJsonObject(JsonReader reader, Politician pol) throws IOException {
    String civilName = null,
           polName = null,
           party = null,
           uf = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String key = reader.nextName();
        if (key.equals(jsonCivilNameKey)) {
            civilName = reader.nextString();
        }
        else if (key.equals(jsonPoliticianNameKey)) {
            polName = reader.nextString();
        }
        else if (key.equals(jsonPartyKey)) {
            party = reader.nextString();
        }
        else if (key.equals(jsonUfKey)) {
            uf = reader.nextString();
        }
        else {
            reader.skipValue();
        }
    }
    reader.endObject();

    pol.setParty(getPartyByAcronym(party));
    pol.setPoliticianName(polName);
    pol.setCivilName(civilName);
    pol.setUf(uf);

    return pol;
}
 
Example 30
Project: lottie-android   File: ShapeTrimPathParser.java   Source Code and License Vote up 5 votes
static ShapeTrimPath parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  String name = null;
  ShapeTrimPath.Type type = null;
  AnimatableFloatValue start = null;
  AnimatableFloatValue end = null;
  AnimatableFloatValue offset = null;

  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "s":
        start = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      case "e":
        end = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      case "o":
        offset = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      case "nm":
        name = reader.nextString();
        break;
      case "m":
        type = ShapeTrimPath.Type.forId(reader.nextInt());
        break;
      default:
        reader.skipValue();
    }
  }

  return new ShapeTrimPath(name, type, start, end, offset);
}
 
Example 31
Project: cosi   File: FileUtils.java   Source Code and License Vote up 5 votes
private static JSONObject readObjectBinary(JsonReader reader) throws IOException, JSONException {
    JSONObject jsonObject = new JSONObject();
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        jsonObject.put(name, readSingleJsonObject(reader));
    }
    reader.endObject();

    Log.d(TAG, jsonObject.toString());

    return jsonObject;
}
 
Example 32
Project: cosi   File: CosiFileService.java   Source Code and License Vote up 5 votes
public List<File> getAllFilesWithJsonReader(InputStream in, NotificationCompat.Builder mBuilder)
        throws IOException, JSONException {
    List<File> allFiles = new ArrayList<>();
    JsonReader jsonReader = new JsonReader(new InputStreamReader(in));
    jsonReader.beginArray();//Start Array
    while (jsonReader.hasNext()) {
        jsonReader.beginObject();//Get parent object
        while (jsonReader.hasNext()) {
            String name = jsonReader.nextName();//Find value attribute
            if (name.equals("value")) {

                File file = parseObjectFile(jsonReader);

                //TODO: Set Progress for notification
                if (mBuilder != null) {
                    //mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Indexing file : " + file.getName());
                    mNotifyManager.notify(notification_id, mBuilder.build());
                }


                EventBus.getDefault().post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator
                        + Constants.APP_DIRECTORY
                        + java.io.File.separator
                        + "files" + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            } else {
                jsonReader.skipValue();//Ignore other attributes
            }
        }//Close parent object
        jsonReader.endObject();
    }//Close array
    jsonReader.endArray();
    return allFiles;
}
 
Example 33
Project: lottie-android   File: KeyframesParser.java   Source Code and License Vote up 5 votes
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;
}
 
Example 34
Project: band-up-android   File: SoundCloudSelectorFragment.java   Source Code and License Vote up 5 votes
/**
 * parse a track from JsonReader and return a new JSONObject
 * with all values we are interested in
 *
 * @param reader
 * @return TrackJsonObject
 */
private JSONObject parseTracksObject(JsonReader reader) {
    JSONObject track = new JSONObject();
    try {
        reader.beginObject();
        while (reader.hasNext()){
            String name = reader.nextName();

            switch (name){
                case "id":
                    track.put("id", reader.nextInt());
                    break;
                case "permalink_url":
                    track.put("permalink_url", reader.nextString());
                    break;
                case "title":
                    track.put("title", reader.nextString());
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();

    } catch (JSONException | IOException e) {
        FirebaseCrash.report(e);
    }
    return track;
}
 
Example 35
Project: lottie-android   File: FontParser.java   Source Code and License Vote up 5 votes
static Font parse(JsonReader reader) throws IOException {
  String family = null;
  String name = null;
  String style = null;
  float ascent = 0;

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "fFamily":
        family = reader.nextString();
        break;
      case "fName":
        name = reader.nextString();
        break;
      case "fStyle":
        style = reader.nextString();
        break;
      case "ascent":
        ascent = (float) reader.nextDouble();
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();

  return new Font(family, name, style, ascent);
}
 
Example 36
Project: lottie-android   File: AnimatableTextPropertiesParser.java   Source Code and License Vote up 5 votes
private static AnimatableTextProperties parseAnimatableTextProperties(
    JsonReader reader, LottieComposition composition) throws IOException {
  AnimatableColorValue color = null;
  AnimatableColorValue stroke = null;
  AnimatableFloatValue strokeWidth = null;
  AnimatableFloatValue tracking = null;

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "fc":
        color = AnimatableValueParser.parseColor(reader, composition);
        break;
      case "sc":
        stroke = AnimatableValueParser.parseColor(reader, composition);
        break;
      case "sw":
        strokeWidth = AnimatableValueParser.parseFloat(reader, composition);
        break;
      case "t":
        tracking = AnimatableValueParser.parseFloat(reader, composition);
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();

  return new AnimatableTextProperties(color, stroke, strokeWidth, tracking);
}
 
Example 37
Project: android-PlacesAutocompleteTextView   File: AndroidPlacesApiJsonParser.java   Source Code and License Vote up 5 votes
List<DescriptionTerm> readDescriptionTermsArray(JsonReader reader) throws IOException {
    List<DescriptionTerm> terms = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        int offset = -1;
        String value = null;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "offset":
                    offset = reader.nextInt();
                    break;
                case "value":
                    value = reader.nextString();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        terms.add(new DescriptionTerm(offset, value));
    }
    reader.endArray();
    return terms;
}
 
Example 38
Project: android-PlacesAutocompleteTextView   File: AndroidPlacesApiJsonParser.java   Source Code and License Vote up 5 votes
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 39
Project: YourPhotosWatch   File: ReaderUtil.java   Source Code and License Vote up 5 votes
static String getText(JsonReader reader) throws IOException, ReaderException {
  String text = null;
  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    if (name.equals("$t"))
      text = reader.nextString();
    else
      reader.skipValue();
  }
  reader.endObject();
  return text;
}
 
Example 40
Project: nexus-gallery   File: FilterGradRepresentation.java   Source Code and License Vote up 5 votes
@Override
public void deSerializeRepresentation(JsonReader sreader) throws IOException {
    sreader.beginObject();
    Vector<Band> points = new Vector<Band>();

    while (sreader.hasNext()) {
        String name = sreader.nextName();
        if (name.startsWith(LINE_NAME)) {
            int pointNo = Integer.parseInt(name.substring(LINE_NAME.length()));
            sreader.beginArray();
            Band p = new Band();
            p.mask = false;
            sreader.hasNext();
            p.xPos1 = sreader.nextInt();
            sreader.hasNext();
            p.yPos1 = sreader.nextInt();
            sreader.hasNext();
            p.xPos2 = sreader.nextInt();
            sreader.hasNext();
            p.yPos2 = sreader.nextInt();
            sreader.hasNext();
            p.brightness = sreader.nextInt();
            sreader.hasNext();
            p.contrast = sreader.nextInt();
            sreader.hasNext();
            p.saturation = sreader.nextInt();
            sreader.hasNext();
            sreader.endArray();
            points.add(p);

        } else {
            sreader.skipValue();
        }
    }
    mBands = points;
    trimVector();
    mCurrentBand = mBands.get(0);
    sreader.endObject();
}
 
Example 41
Project: autoparse-json   File: UnannotatedObjectParser.java   Source Code and License Vote up 5 votes
private void parseFromReader(UnannotatedObject out, JsonReader reader) throws IOException {
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case "string": {
                out.string = reader.nextString();
                break;
            }
            default: {
                reader.skipValue();
            }
        }
    }
}
 
Example 42
Project: android-PlacesAutocompleteTextView   File: AndroidPlacesApiJsonParser.java   Source Code and License Vote up 5 votes
List<MatchedSubstring> readMatchedSubstringsArray(JsonReader reader) throws IOException {
    List<MatchedSubstring> matchedSubstrings = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {
        int length = -1;
        int offset = -1;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
                case "length":
                    length = reader.nextInt();
                    break;
                case "offset":
                    offset = reader.nextInt();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        matchedSubstrings.add(new MatchedSubstring(length, offset));
    }
    reader.endArray();
    return matchedSubstrings;
}
 
Example 43
Project: GitHub   File: BooleansRealmProxy.java   Source Code and License Vote up 4 votes
@SuppressWarnings("cast")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static some.test.Booleans createUsingJsonStream(Realm realm, JsonReader reader)
        throws IOException {
    final some.test.Booleans obj = new some.test.Booleans();
    final BooleansRealmProxyInterface objProxy = (BooleansRealmProxyInterface) obj;
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (false) {
        } else if (name.equals("done")) {
            if (reader.peek() != JsonToken.NULL) {
                objProxy.realmSet$done((boolean) reader.nextBoolean());
            } else {
                reader.skipValue();
                throw new IllegalArgumentException("Trying to set non-nullable field 'done' to null.");
            }
        } else if (name.equals("isReady")) {
            if (reader.peek() != JsonToken.NULL) {
                objProxy.realmSet$isReady((boolean) reader.nextBoolean());
            } else {
                reader.skipValue();
                throw new IllegalArgumentException("Trying to set non-nullable field 'isReady' to null.");
            }
        } else if (name.equals("mCompleted")) {
            if (reader.peek() != JsonToken.NULL) {
                objProxy.realmSet$mCompleted((boolean) reader.nextBoolean());
            } else {
                reader.skipValue();
                throw new IllegalArgumentException("Trying to set non-nullable field 'mCompleted' to null.");
            }
        } else if (name.equals("anotherBoolean")) {
            if (reader.peek() != JsonToken.NULL) {
                objProxy.realmSet$anotherBoolean((boolean) reader.nextBoolean());
            } else {
                reader.skipValue();
                throw new IllegalArgumentException("Trying to set non-nullable field 'anotherBoolean' to null.");
            }
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return realm.copyToRealm(obj);
}
 
Example 44
Project: RNLearn_Project1   File: JSDebuggerWebSocketClient.java   Source Code and License Vote up 4 votes
@Override
public void onMessage(ResponseBody response) throws IOException {
  if (response.contentType() != WebSocket.TEXT) {
    FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType());
    return;
  }

  Integer replyID = null;

  try {
    JsonReader reader = new JsonReader(response.charStream());
    String result = null;
    reader.beginObject();
    while (reader.hasNext()) {
      String field = reader.nextName();

      if (JsonToken.NULL == reader.peek()) {
        reader.skipValue();
        continue;
      }

      if ("replyID".equals(field)) {
        replyID = reader.nextInt();
      } else if ("result".equals(field)) {
        result = reader.nextString();
      } else if ("error".equals(field)) {
        String error = reader.nextString();
        abort(error, new JavascriptException(error));
      }
    }
    if (replyID != null) {
      triggerRequestSuccess(replyID, result);
    }
  } catch (IOException e) {
    if (replyID != null) {
      triggerRequestFailure(replyID, e);
    } else {
      abort("Parsing response message from websocket failed", e);
    }
  } finally {
    response.close();
  }
}
 
Example 45
Project: ExoPlayer-Offline   File: SampleChooserActivity.java   Source Code and License Vote up 4 votes
private Sample readEntry(JsonReader reader, boolean insidePlaylist) throws IOException {
  String sampleName = null;
  String uri = null;
  String extension = null;
  UUID drmUuid = null;
  String drmLicenseUrl = null;
  String[] drmKeyRequestProperties = null;
  boolean preferExtensionDecoders = false;
  ArrayList<UriSample> playlistSamples = null;

  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    switch (name) {
      case "name":
        sampleName = reader.nextString();
        break;
      case "uri":
        uri = reader.nextString();
        break;
      case "extension":
        extension = reader.nextString();
        break;
      case "drm_scheme":
        Assertions.checkState(!insidePlaylist, "Invalid attribute on nested item: drm_scheme");
        drmUuid = getDrmUuid(reader.nextString());
        break;
      case "drm_license_url":
        Assertions.checkState(!insidePlaylist,
            "Invalid attribute on nested item: drm_license_url");
        drmLicenseUrl = reader.nextString();
        break;
      case "drm_key_request_properties":
        Assertions.checkState(!insidePlaylist,
            "Invalid attribute on nested item: drm_key_request_properties");
        ArrayList<String> drmKeyRequestPropertiesList = new ArrayList<>();
        reader.beginObject();
        while (reader.hasNext()) {
          drmKeyRequestPropertiesList.add(reader.nextName());
          drmKeyRequestPropertiesList.add(reader.nextString());
        }
        reader.endObject();
        drmKeyRequestProperties = drmKeyRequestPropertiesList.toArray(new String[0]);
        break;
      case "prefer_extension_decoders":
        Assertions.checkState(!insidePlaylist,
            "Invalid attribute on nested item: prefer_extension_decoders");
        preferExtensionDecoders = reader.nextBoolean();
        break;
      case "playlist":
        Assertions.checkState(!insidePlaylist, "Invalid nesting of playlists");
        playlistSamples = new ArrayList<>();
        reader.beginArray();
        while (reader.hasNext()) {
          playlistSamples.add((UriSample) readEntry(reader, true));
        }
        reader.endArray();
        break;
      default:
        throw new ParserException("Unsupported attribute name: " + name);
    }
  }
  reader.endObject();

  if (playlistSamples != null) {
    UriSample[] playlistSamplesArray = playlistSamples.toArray(
        new UriSample[playlistSamples.size()]);
    return new PlaylistSample(sampleName, drmUuid, drmLicenseUrl, drmKeyRequestProperties,
        preferExtensionDecoders, playlistSamplesArray);
  } else {
    return new UriSample(sampleName, drmUuid, drmLicenseUrl, drmKeyRequestProperties,
        preferExtensionDecoders, uri, extension);
  }
}
 
Example 46
Project: MediaNotification   File: AboutDialog.java   Source Code and License Vote up 4 votes
@Override
public void run() {
    try {
        HttpURLConnection request = (HttpURLConnection) new URL("https://api.github.com/repos/TheAndroidMaster/MediaNotification/contributors").openConnection();
        request.connect();

        JsonReader reader = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
        reader.setLenient(true);
        reader.beginArray();
        reader.skipValue();
        while (reader.hasNext()) {
            reader.beginObject();
            String name = null, imageUrl = null, url = null;
            while (reader.hasNext()) {
                switch (reader.nextName()) {
                    case "login":
                        name = reader.nextString();
                        break;
                    case "avatar_url":
                        imageUrl = reader.nextString();
                        break;
                    case "html_url":
                        url = reader.nextString();
                        break;
                    default:
                        reader.skipValue();
                }
            }
            contributors.add(new ContributorData(name, imageUrl, url));
            reader.endObject();
        }
        reader.endArray();
    } catch (Exception ignored) {
    }

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            AboutDialog dialog = dialogReference.get();
            if (dialog != null) {
                dialog.contributorView.getAdapter().notifyDataSetChanged();
                for (final ContributorData contributor : contributors) {
                    new ContributorThread(dialog, contributor).start();
                }
            }
        }
    });
}
 
Example 47
Project: RNLearn_Project1   File: JSDebuggerWebSocketClient.java   Source Code and License Vote up 4 votes
@Override
public void onMessage(ResponseBody response) throws IOException {
  if (response.contentType() != WebSocket.TEXT) {
    FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType());
    return;
  }

  Integer replyID = null;

  try {
    JsonReader reader = new JsonReader(response.charStream());
    String result = null;
    reader.beginObject();
    while (reader.hasNext()) {
      String field = reader.nextName();

      if (JsonToken.NULL == reader.peek()) {
        reader.skipValue();
        continue;
      }

      if ("replyID".equals(field)) {
        replyID = reader.nextInt();
      } else if ("result".equals(field)) {
        result = reader.nextString();
      } else if ("error".equals(field)) {
        String error = reader.nextString();
        abort(error, new JavascriptException(error));
      }
    }
    if (replyID != null) {
      triggerRequestSuccess(replyID, result);
    }
  } catch (IOException e) {
    if (replyID != null) {
      triggerRequestFailure(replyID, e);
    } else {
      abort("Parsing response message from websocket failed", e);
    }
  } finally {
    response.close();
  }
}
 
Example 48
Project: SSTVEncoder2   File: Settings.java   Source Code and License Vote up 4 votes
private int readVersion(JsonReader reader) throws IOException {
    reader.nextName();
    return reader.nextInt();
}
 
Example 49
Project: SSTVEncoder2   File: Settings.java   Source Code and License Vote up 4 votes
private void readModeClassName(JsonReader reader) throws IOException {
    reader.nextName();
    mModeClassName = reader.nextString();
}
 
Example 50
Project: AOSP-Kayboard-7.1.2   File: MetadataParser.java   Source Code and License Vote up 4 votes
/**
 * Parse one JSON-formatted word list metadata.
 * @param reader the reader containing the data.
 * @return a WordListMetadata object from the parsed data.
 * @throws IOException if the underlying reader throws IOException during reading.
 */
private static WordListMetadata parseOneWordList(final JsonReader reader)
        throws IOException, BadFormatException {
    final TreeMap<String, String> arguments = new TreeMap<>();
    reader.beginObject();
    while (reader.hasNext()) {
        final String name = reader.nextName();
        if (!TextUtils.isEmpty(name)) {
            arguments.put(name, reader.nextString());
        }
    }
    reader.endObject();
    if (TextUtils.isEmpty(arguments.get(ID_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(LOCALE_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(DESCRIPTION_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(UPDATE_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(FILESIZE_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(CHECKSUM_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(REMOTE_FILENAME_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(VERSION_FIELD_NAME))
            || TextUtils.isEmpty(arguments.get(FORMATVERSION_FIELD_NAME))) {
        throw new BadFormatException(arguments.toString());
    }
    // TODO: need to find out whether it's bulk or update
    // The null argument is the local file name, which is not known at this time and will
    // be decided later.
    return new WordListMetadata(
            arguments.get(ID_FIELD_NAME),
            MetadataDbHelper.TYPE_BULK,
            arguments.get(DESCRIPTION_FIELD_NAME),
            Long.parseLong(arguments.get(UPDATE_FIELD_NAME)),
            Long.parseLong(arguments.get(FILESIZE_FIELD_NAME)),
            arguments.get(RAW_CHECKSUM_FIELD_NAME),
            arguments.get(CHECKSUM_FIELD_NAME),
            MetadataDbHelper.DICTIONARY_RETRY_THRESHOLD /* retryCount */,
            null,
            arguments.get(REMOTE_FILENAME_FIELD_NAME),
            Integer.parseInt(arguments.get(VERSION_FIELD_NAME)),
            Integer.parseInt(arguments.get(FORMATVERSION_FIELD_NAME)),
            0, arguments.get(LOCALE_FIELD_NAME));
}
 
Example 51
Project: lighthouse   File: PodcastJsonParser.java   Source Code and License Vote up 4 votes
@Nullable
private static Record parseRecord(JsonReader parser, @Nullable URI uri) throws IOException {
    long id = 0;
    String url = null;
    String name = null;
    String description = null;
    String date = null;
    String duration = null;

    parser.beginObject();
    while (parser.hasNext()) {
        String prop = parser.nextName();
        if (AUDIO_PROPERTY.equals(prop)) {
            parser.beginArray();
            if (parser.hasNext()) {
                parser.beginObject();
                while (parser.hasNext()) {
                    String audioProp = parser.nextName();
                    if (SOURCES_PROPERTY.equals(audioProp)) {
                        parser.beginObject();
                        while (parser.hasNext()) {
                            String sourcesProp = parser.nextName();
                            if (URL_PROPERTY.equals(sourcesProp)) {
                                url = StringUtils.nonEmpty(parser.nextString());
                            } else {
                                parser.skipValue();
                            }
                        }
                        parser.endObject();
                    } else if (ID_PROPERTY.equals(audioProp)) {
                        id = parser.nextLong();
                    } else if (DATE_PROPERTY.equals(audioProp)) {
                        date = extractDate(parser.nextString());
                    } else if (DURATION_PROPERTY.equals(audioProp)) {
                        duration = extractDuration(parser.nextString());
                    } else {
                        parser.skipValue();
                    }
                }
                parser.endObject();
            }
            while (parser.hasNext()) {
                parser.skipValue();
            }
            parser.endArray();
        } else if (NAME_PROPERTY.equals(prop)) {
            name = StringUtils.nonEmpty(parser.nextString());
        } else if (DESCRIPTION_PROPERTY.equals(prop)) {
            description = StringUtils.nonEmpty(parser.nextString());
            if (description != null) {
                description = LayoutUtils.clean(description);
            }
        } else {
            parser.skipValue();
        }
    }
    parser.endObject();

    if (url == null || name == null) {
        return null;
    }
    if (id == 0) {
        id = StringUtils.parseLong(extractId(url), 0);
        if (id == 0) {
            return null;
        }
    }
    Record record = new Record(id, name, url, uri);
    record.setDescription(description);
    record.setDate(date);
    record.setDuration(duration);
    return record;
}
 
Example 52
Project: DietDiaryApp   File: RestoreDialog.java   Source Code and License Vote up 4 votes
@Override
protected void start(InputStreamReader inputStream, Resources resources) throws IOException {
    reader = new JsonReader(inputStream);

    String[] types = resources.getStringArray(R.array.spinner_event_types);
    typesMap = new HashMap<>(types.length);
    for (int i = 0; i < types.length; i++) {
        typesMap.put(types[i], i);
    }

    String[] foodTypes = resources.getStringArray(R.array.spinner_event_food_types);
    foodTypesMap = new HashMap<>(types.length);
    for (int i = 0; i < foodTypes.length; i++) {
        foodTypesMap.put(foodTypes[i], i);
    }

    String[] drinkTypes = resources.getStringArray(R.array.spinner_event_drink_types);
    drinkTypesMap = new HashMap<>(types.length);
    for (int i = 0; i < drinkTypes.length; i++) {
        drinkTypesMap.put(drinkTypes[i], i);
    }

    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "App":
                reader.skipValue();
                break;
            case "Ver":
                reader.skipValue();
                break;
            case "Device":
                reader.skipValue();
                break;
            case "Settings":
                reader.skipValue();
                // TODO: Read and apply previous settings.
                break;
            case "Events":
                reader.beginArray();
                return; // This will be read @readNext()
        }
    }
}
 
Example 53
Project: lottie-android   File: AnimatableTransformParser.java   Source Code and License Vote up 4 votes
public static AnimatableTransform parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  AnimatablePathValue anchorPoint = null;
  AnimatableValue<PointF, PointF> position = null;
  AnimatableScaleValue scale = null;
  AnimatableFloatValue rotation = null;
  AnimatableIntegerValue opacity = null;
  AnimatableFloatValue startOpacity = null;
  AnimatableFloatValue endOpacity = null;

  boolean isObject = reader.peek() == JsonToken.BEGIN_OBJECT;
  if (isObject) {
    reader.beginObject();
  }
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "a":
        reader.beginObject();
        while (reader.hasNext()) {
          if (reader.nextName().equals("k")) {
            anchorPoint = AnimatablePathValueParser.parse(reader, composition);
          } else {
            reader.skipValue();
          }
        }
        reader.endObject();
        break;
      case "p":
        position =
            AnimatablePathValueParser.parseSplitPath(reader, composition);
        break;
      case "s":
        scale = AnimatableValueParser.parseScale(reader, composition);
        break;
      case "rz":
        composition.addWarning("Lottie doesn't support 3D layers.");
      case "r":
        rotation = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      case "o":
        opacity = AnimatableValueParser.parseInteger(reader, composition);
        break;
      case "so":
        startOpacity = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      case "eo":
        endOpacity = AnimatableValueParser.parseFloat(reader, composition, false);
        break;
      default:
        reader.skipValue();
    }
  }
  if (isObject) {
    reader.endObject();
  }

  if (anchorPoint == null) {
    // Cameras don't have an anchor point property. Although we don't support them, at least
    // we won't crash.
    Log.w(L.TAG, "Layer has no transform property. You may be using an unsupported " +
        "layer type such as a camera.");
    anchorPoint = new AnimatablePathValue();
  }

  if (scale == null) {
    // Somehow some community animations don't have scale in the transform.
    scale = new AnimatableScaleValue(new ScaleXY(1f, 1f));
  }

  if (opacity == null) {
    // Repeaters have start/end opacity instead of opacity
    opacity = new AnimatableIntegerValue();
  }

  return new AnimatableTransform(
      anchorPoint, position, scale, rotation, opacity, startOpacity, endOpacity);
}
 
Example 54
Project: lottie-android   File: GradientFillParser.java   Source Code and License Vote up 4 votes
static GradientFill parse(
    JsonReader reader, LottieComposition composition) throws IOException {
  String name = null;
  AnimatableGradientColorValue color = null;
  AnimatableIntegerValue opacity = null;
  GradientType gradientType = null;
  AnimatablePointValue startPoint = null;
  AnimatablePointValue endPoint = null;
  Path.FillType fillType = null;

  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "nm":
        name = reader.nextString();
        break;
      case "g":
        int points = -1;
        reader.beginObject();
        while (reader.hasNext()) {
          switch (reader.nextName()) {
            case "p":
              points = reader.nextInt();
              break;
            case "k":
              color = AnimatableValueParser.parseGradientColor(reader, composition, points);
              break;
            default:
              reader.skipValue();
          }
        }
        reader.endObject();
        break;
      case "o":
        opacity = AnimatableValueParser.parseInteger(reader, composition);
        break;
      case "t":
        gradientType = reader.nextInt() == 1 ? GradientType.Linear : GradientType.Radial;
        break;
      case "s":
        startPoint = AnimatableValueParser.parsePoint(reader, composition);
        break;
      case "e":
        endPoint = AnimatableValueParser.parsePoint(reader, composition);
        break;
      case "r":
        fillType = reader.nextInt() == 1 ? Path.FillType.WINDING : Path.FillType.EVEN_ODD;
        break;
      default:
        reader.skipValue();
    }
  }

  return new GradientFill(
      name, gradientType, fillType, color, opacity, startPoint, endPoint, null, null);
}
 
Example 55
Project: lottie-android   File: LottieCompositionParser.java   Source Code and License Vote up 4 votes
public static LottieComposition parse(JsonReader reader) throws IOException {
  float scale = Utils.dpScale();
  float startFrame = 0f;
  float endFrame = 0f;
  float frameRate = 0f;
  int majorVersion = 0;
  int minorVersion = 0;
  int patchVersion = 0;
  final LongSparseArray<Layer> layerMap = new LongSparseArray<>();
  final List<Layer> layers = new ArrayList<>();
  int width = 0;
  int height = 0;
  Map<String, List<Layer>> precomps = new HashMap<>();
  Map<String, LottieImageAsset> images = new HashMap<>();
  Map<String, Font> fonts = new HashMap<>();
  SparseArrayCompat<FontCharacter> characters = new SparseArrayCompat<>();

  LottieComposition composition = new LottieComposition();

  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "w":
        width = reader.nextInt();
        break;
      case "h":
        height = reader.nextInt();
        break;
      case "ip":
        startFrame = (float) reader.nextDouble();
        break;
      case "op":
        endFrame = (float) reader.nextDouble();
        break;
      case "fr":
        frameRate = (float) reader.nextDouble();
        break;
      case "v":
        String version = reader.nextString();
        String[] versions = version.split("\\.");
        majorVersion = Integer.parseInt(versions[0]);
        minorVersion = Integer.parseInt(versions[1]);
        patchVersion = Integer.parseInt(versions[2]);
        if (!Utils.isAtLeastVersion(composition, 4, 5, 0)) {
          composition.addWarning("Lottie only supports bodymovin >= 4.5.0");
        }
        break;
      case "layers":
        parseLayers(reader, composition, layers, layerMap);
        break;
      case "assets":
        parseAssets(reader, composition, precomps, images);
        break;
      case "fonts":
        parseFonts(reader, fonts);
        break;
      case "chars":
        parseChars(reader, composition, characters);
        break;
      default:
        reader.skipValue();
    }
  }
  reader.endObject();

  int scaledWidth = (int) (width * scale);
  int scaledHeight = (int) (height * scale);
  Rect bounds = new Rect(0, 0, scaledWidth, scaledHeight);

  composition.init(bounds, startFrame, endFrame, frameRate, majorVersion, minorVersion,
      patchVersion, layers, layerMap, precomps, images, characters, fonts);

  return composition;
}
 
Example 56
Project: cosi   File: CosiFileService.java   Source Code and License Vote up 4 votes
private File parseObjectFolder(JsonReader jsonReader) throws IOException {
    File file = new File();
    jsonReader.beginObject();//Get child object from value attribute
    while (jsonReader.hasNext()) {
        String name = jsonReader.nextName();
        if (name.equals("_id")) {
            String remoteId = jsonReader.nextString();
            Log.d("ParseJsonTest", remoteId);
            file = File.getByRemoteId(remoteId);
            if (file == null) {
                file = new File();
                file.setRemoteId(remoteId);
            }
        } else if (name.equals("name")) {
            file.setName(jsonReader.nextString());
        } else if (name.equals("path")) {
            String path = jsonReader.nextString();
            file.setPath(path);
        } else if (name.equals("creationDate")) {
            file.setCreationDate(jsonReader.nextString());
        } else if (name.equals("lastModification")) {
            file.setLastModification(jsonReader.nextString());
        } else if (name.equals("tags")) {
            jsonReader.beginArray();
            ArrayList<String> tags = new ArrayList<>();
            while (jsonReader.hasNext()) {
                tags.add(jsonReader.nextString());
            }
            jsonReader.endArray();
            Log.d("ParseJsonTags", tags.toString());
            file.setTags(tags.toString());
        } else {
            jsonReader.skipValue();
        }
    }//Close child object from value attribute

    jsonReader.endObject();
    file.setBinary("");
    file.setIsFile(false);
    file.setFileClass("");
    file.setMimeType("");
    file.setSize(Long.valueOf(0));
    return file;
}
 
Example 57
Project: autoparse-json   File: JsonParserUtils.java   Source Code and License Vote up 4 votes
/**
 * Call this method when parsing an object, the parser type is unknown, and the first name
 * inside the object was the discrimination name. This method will add all values to a {@link
 * JSONObject} until the discrimination name and a matching parser are found. If no matching
 * parser is ever found, then this method returns the JSONObject.
 *
 * @param reader The reader to use.
 * @param firstName The first name parsed in this object so far. May be null, but the next toke
 * in the JsonReader should be a {@link JsonToken#NAME}.
 * @param firstValue The first value parse in this object so far. May be null, and if {@code
 * firstName} is not null, the next token in the JsonReader should be a value type.
 *
 * @return A custom object or a JSONObject if no appropriate parser was found.
 */
private static Object parseSpecificJsonObjectDelayed(JsonReader reader,
                                                     String firstName,
                                                     Object firstValue)
        throws IOException {
    final String discriminationName =
            ContextHolder.getContext().getSettings().getDiscriminationName();
    JSONObject jsonObject = new JSONObject();
    String name = firstName;
    Object value = firstValue;

    if (name == null && reader.hasNext()) {
        name = reader.nextName();
    }
    if (value == null && name != null) {
        value = parseNextValue(reader, false);
    }

    while (name != null) {
        if (discriminationName.equals(name)) {
            if (!(value instanceof String)) {
                throwDiscriminationValueException(discriminationName, value);
            }
            final String discriminationValue = (String) value;
            JsonObjectParser<?> parser = ContextHolder.getContext()
                                                      .getJsonObjectParserTable()
                                                      .get(discriminationValue);
            if (parser != null) {
                return parser.parseJsonObject(jsonObject,
                                              reader,
                                              discriminationName,
                                              discriminationValue);
            }
        }

        // No matching parser has been found yet; save the current name and value to the
        // jsonObject.
        try {
            jsonObject.put(name, value);
        } catch (JSONException e) {
            // this should only happen if the name is null, which is impossible here.
            throw new RuntimeException("This should be impossible.", e);
        }

        if (reader.hasNext()) {
            name = reader.nextName();
            value = parseNextValue(reader, false);
        } else {
            name = null;
            value = null;
        }
    }
    return jsonObject;
}
 
Example 58
Project: SchulinfoApp-android   File: News.java   Source Code and License Vote up 4 votes
@Override
public boolean load() {
    clear();
    try {
        InputStream in = SIAApp.SIA_APP.openFileInput("news");
        JsonReader reader = new JsonReader(new InputStreamReader(in));
        reader.beginArray();
        while(reader.hasNext()) {
            reader.beginObject();
            Entry s = new Entry();

            while(reader.hasNext()) {
                String name = reader.nextName();
                switch (name) {
                    case "id":
                        s.id = reader.nextString();
                        break;
                    case "date":
                        s.date = new Date(reader.nextLong());
                        break;
                    case "topic":
                        s.topic = reader.nextString();
                        break;
                    case "source":
                        s.source = reader.nextString();
                        break;
                    case "title":
                        s.title = reader.nextString();
                        break;
                    case "text":
                        s.text = reader.nextString();
                        break;
                    default:
                        reader.skipValue();
                        break;
                }
            }
            reader.endObject();
            add(s);
        }
        reader.endArray();
        reader.close();
    } catch(Exception e) {
        Log.w("ggvp", "News file does not exist");
        return false;
    }

    return true;
}
 
Example 59
Project: learnforandroidfragAS   File: fragFileChooserQuizlet.java   Source Code and License Vote up 4 votes
typVok parseSetDataJson( JsonReader reader ) throws IOException {
	reader.beginObject();
	typVok rowData = new typVok();

	while ( reader.hasNext() ) {
		String name = reader.nextName();
		if ( name.equals( "term" )) {
			rowData.Wort = reader.nextString();
		}
		else if ( name.equals( "id" )) {
			long id = reader.nextLong();
			rowData.z = 0;
		}
		else if ( name.equals( "definition" )) {
			rowData.Bed1 = reader.nextString();
			rowData.Bed2 = "";
			rowData.Bed3 = "";
		}
		else if ( name.equals( "image" )) {
			try
			{
				reader.beginObject();
				while ( reader.hasNext() ) {
					String strName = reader.nextName();
					if ( strName.equals( "url" )) {
						String value = "<link://" + reader.nextString() + " " + _main.getString(R.string.picture) +  "/>";
						rowData.Kom = value;
					}
					else
					{
						reader.skipValue();
					}
				}
				reader.endObject();
			}
			catch (Throwable exception)
			{
				reader.skipValue();
				//String value = "<link://" + reader.nextString() + "/>";
				//rowData.Kom = value;
			}

		}
		else {
			reader.skipValue();
		}
	}
	reader.endObject();
	if (lib.libString.IsNullOrEmpty(rowData.Bed1)) {
		rowData.Bed1 = rowData.Kom;
		rowData.Bed2 = "";
		rowData.Bed3 = "";
	}
	return rowData ;
}
 
Example 60
Project: learnforandroidfragAS   File: fragFileChooserQuizlet.java   Source Code and License Vote up 4 votes
private List<RowData> openPage() throws Exception {
	this.errorDescription = null ;
	this.errorTitle = null ;

	List<RowData> list = new ArrayList<RowData>();
	InputStream inputStream = null ;
	try {
		if (!blnPrivate)
		{
			URL url = new URL( getCatalogUrl() );
		/*HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		if ( connection.getResponseCode() >= 400 ) {
			inputStream = connection.getErrorStream();
		}
		else {
			inputStream = connection.getInputStream();
		}*/
			inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.makeApiCall(url,_main.QuizletAccessToken);
		}
		else
		{
			inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.getUserPrivateCardsets(_main.QuizletUser,_main.QuizletAccessToken);
		}
		JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
		if (!blnPrivate) {
			reader.beginObject();
			while (reader.hasNext()) {
				String name = reader.nextName();
				if ("total_pages".equals(name)) {
					this.totalPages = reader.nextInt();
					if (page > totalPages) {

					}
				} else if ("total_results".equals(name)) {
					this.totalResults = reader.nextInt();
				} else if ("page".equals(name)) {
					this.page = reader.nextInt();
				} else if ("error_title".equals(name)) {
					errorTitle = reader.nextString();
				} else if ("error_description".equals(name)) {
					errorDescription = reader.nextString();
				} else if ("sets".equals(name)) {
					getSets(reader, list);
				} else {
					reader.skipValue();
				}
			}
			reader.endObject();
		}
		else
		{
			getSets(reader,list);
		}

	}
	finally {
		if ( inputStream != null ) {
			inputStream.close();
		}
	}
	return list ;
}