Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject optJSONArray.

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void getPostMissing() {
    notificationService();/*from  w w w .  j  a v a 2  s  .  c o m*/
    SharedPrefs.getInstance().setDownloading(true);
    DatabaseManager databaseManager = new DatabaseManager(this);
    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";
    Request request = new Request.Builder().url(firstUrl).build();
    int count = 0;

    try {

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();

        //Take the response and parse the JSON
        JSONObject JObject = new JSONObject(response.body().string());
        JSONArray posts = JObject.optJSONArray("posts");

        //Store the data into the two objects, meta gets the next page later on.
        // Found is total post count.
        String meta = JObject.optString("meta");
        int found = JObject.optInt("found");

        postID = new ArrayList<>();

        //If there are more then 100, which there always will unless something
        // catastrophic happens then set up the newURL.
        if (found > 100) {
            JSONObject metaLink = new JSONObject(meta);
            String nextValue = metaLink.optString("next_page");
            newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
        }

        // Loop through the posts and add the post ID to the array.
        // The posts is still from the original call.
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            if (!databaseManager.idExists(post.optString("ID"))) {
                postID.add(post.optString("ID"));
            }
            count++;
        }

        //Now this logic is in charge of loading the next pages
        // until all posts are loaded into the array.
        while (count != found) {
            Request newRequest = new Request.Builder().url(newURL).build();
            Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
            if (!newResponse.isSuccessful())
                throw new IOException();

            JSONObject nJObject = new JSONObject(newResponse.body().string());
            JSONArray nPosts = nJObject.optJSONArray("posts");
            String nMeta = nJObject.optString("meta");
            int newFound = nJObject.optInt("found");

            if (newFound > 100) {
                JSONObject metaLink = new JSONObject(nMeta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");

            }

            for (int i = 0; i < nPosts.length(); i++) {
                JSONObject post = nPosts.optJSONObject(i);
                if (!databaseManager.idExists(post.optString("ID"))) {
                    postID.add(post.optString("ID"));
                }
                count++;
            }
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
    Collections.reverse(postID);
    download(postID);
}

From source file:com.melniqw.instagramsdk.Media.java

public static Media fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Media media = new Media();
    media.id = o.optString("id");
    media.type = o.optString("type");
    media.createdTime = o.optString("created_time");
    media.attribution = o.optString("attribution");
    media.image = Image.fromJSON(o.optJSONObject("images"));
    if (media.type.equals("video"))
        media.video = Video.fromJSON(o.optJSONObject("videos"));
    media.link = o.optString("link");
    media.filter = o.optString("filter");
    media.userHasLiked = o.optBoolean("user_has_liked");
    media.user = User.fromJSON(o.optJSONObject("user"));
    JSONArray tagsJSONArray = o.optJSONArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (int j = 0; j < tagsJSONArray.length(); j++) {
        tags.add(tagsJSONArray.optString(j));
    }/*  w  ww. ja  va 2 s.c om*/
    media.tags.addAll(tags);
    JSONArray likesJSONArray = o.optJSONObject("likes").optJSONArray("data");
    ArrayList<Like> likes = new ArrayList<>();
    for (int j = 0; j < likesJSONArray.length(); j++) {
        JSONObject likeJSON = (JSONObject) likesJSONArray.get(j);
        likes.add(Like.fromJSON(likeJSON));
    }
    media.likes.addAll(likes);
    JSONArray commentJSONArray = o.optJSONObject("comments").optJSONArray("data");
    ArrayList<Comment> comments = new ArrayList<>();
    for (int j = 0; j < commentJSONArray.length(); j++) {
        JSONObject commentJSON = (JSONObject) commentJSONArray.get(j);
        comments.add(Comment.fromJSON(commentJSON));
    }
    media.comments.addAll(comments);
    JSONArray usersInPhotoJSON = o.optJSONArray("users_in_photo");
    ArrayList<UserInPhoto> usersInPhotos = new ArrayList<>();
    for (int j = 0; j < usersInPhotoJSON.length(); j++) {
        JSONObject userInPhotoJSON = (JSONObject) usersInPhotoJSON.get(j);
        usersInPhotos.add(UserInPhoto.fromJSON(userInPhotoJSON));
    }
    media.usersInPhoto.addAll(usersInPhotos);
    JSONObject locationJSON = o.optJSONObject("location");
    if (locationJSON != null) {
        media.location = Location.fromJSON(locationJSON);
    }
    JSONObject captionJSON = o.optJSONObject("caption");
    if (captionJSON != null) {
        media.caption = Comment.fromJSON(captionJSON);
    }
    return media;
}

From source file:kr.ac.cau.mecs.cass.processor.CASLaunchProcessor.java

@Override
public Signal process(Signal signal) {
    Signal resignal = new Signal();

    resignal.setReceiver(signal.getSender());
    resignal.setSender("CASS");
    resignal.setAction(new Action(Action.ACT_LAUNCH));

    if (currentUser != null) {
        JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData();

        System.out.println(jobj.toString());

        JSONObject jcau = jobj.optJSONObject("cau");
        JSONObject jaction = jobj.optJSONObject("action");
        JSONArray jsensor = jobj.optJSONArray("sensor");

        CAUEntity cau = CAUEntity.fromJSONObject(jcau);
        ActionEntity action = ActionEntity.fromJSONObject(jaction);

        //see if user already has cau entry of that name
        DBCAUEntity dbcau = findCAU(cau.getName(), cau.getVersion());
        if (dbcau == null) {
            //create new cau here!
            dbcau = new DBCAUEntity();
            dbcau.setName(cau.getName());
            dbcau.setVersion(cau.getVersion());
            dbcau.setUser(currentUser);//from   w w w .  j a va  2  s .  c  o m
            dbcau.setActions(new HashSet<DBActionEntity>());
        }

        //see if cau has that action already
        DBActionEntity dbaction = null;

        for (DBActionEntity tmp : dbcau.getActions()) {
            if (tmp.getAid() == action.getAid()) {
                dbaction = tmp;
                break;
            }
        }
        //create new action here!
        if (dbaction == null) {
            dbaction = new DBActionEntity();
            dbaction.setAid(action.getAid());
            dbaction.setCau(dbcau);
            dbaction.setName(action.getName());
            dbaction.setSensordata(new HashSet<DBSensorEntity>());
        }

        //create new sensor entry

        for (int i = 0; i < jsensor.length(); i++) {
            SensorEntity sensor = SensorEntity.fromJSONObject(jsensor.getJSONObject(i));
            DBSensorEntity dbsensor = new DBSensorEntity();

            dbsensor.setAction(dbaction);
            dbsensor.setDataType(sensor.getDataType());
            dbsensor.setCaeType(sensor.getCaeType());
            dbsensor.setSensorName(sensor.getSensorName());
            dbsensor.setTimestamp(sensor.getTimestamp());
            dbsensor.setValue(sensor.getValue());

            session.saveOrUpdate(dbsensor);
        }
        session.saveOrUpdate(dbcau);
        session.saveOrUpdate(dbaction);

    } else {
        setGenericMessage(resignal, "invalid credential");
    }

    return resignal;
}

From source file:com.phelps.liteweibo.model.weibo.GroupList.java

public static GroupList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }// w  ww .  j a v  a  2s  . c o m

    GroupList groupList = new GroupList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        groupList.total_number = jsonObject.optInt("total_number");

        JSONArray jsonArray = jsonObject.optJSONArray("lists");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            groupList.groupList = new ArrayList<Group>(length);
            for (int ix = 0; ix < length; ix++) {
                groupList.groupList.add(Group.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return groupList;
}

From source file:com.rapid.actions.Group.java

public Group(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();//from  w ww .  ja v a 2  s . co m
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for the ones we want directly accessible
        if (!"actions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // grab any actions
    JSONArray jsonActions = jsonAction.optJSONArray("actions");
    // if we had some
    if (jsonActions != null) {
        _actions = Control.getActions(rapidServlet, jsonActions);
    }

}

From source file:com.github.mhendred.face4j.model.Face.java

public Face(JSONObject jObj) throws JSONException {
    tid = jObj.getString("tid");
    label = jObj.optString("label");

    confirmed = jObj.getBoolean("confirmed");
    manual = jObj.getBoolean("manual");

    width = (float) jObj.getDouble("width");
    height = (float) jObj.getDouble("height");

    yaw = (float) jObj.getDouble("yaw");
    roll = (float) jObj.getDouble("roll");
    pitch = (float) jObj.getDouble("pitch");

    threshold = jObj.optInt("threshold");

    center = fromJson(jObj.optJSONObject("center"));

    leftEye = fromJson(jObj.optJSONObject("eye_left"));
    rightEye = fromJson(jObj.optJSONObject("eye_right"));

    leftEar = fromJson(jObj.optJSONObject("ear_left"));
    rightEar = fromJson(jObj.optJSONObject("ear_right"));

    chin = fromJson(jObj.optJSONObject("chin"));

    mouthCenter = fromJson(jObj.optJSONObject("mouth_center"));
    mouthRight = fromJson(jObj.optJSONObject("mouth_right"));
    mouthLeft = fromJson(jObj.optJSONObject("mouth_left"));

    nose = fromJson(jObj.optJSONObject("nose"));

    guesses = Guess.fromJsonArray(jObj.optJSONArray("uids"));

    // Attributes
    jObj = jObj.getJSONObject("attributes");

    if (jObj.has("smiling"))
        smiling = jObj.getJSONObject("smiling").getBoolean("value");

    if (jObj.has("glasses"))
        glasses = jObj.getJSONObject("glasses").getBoolean("value");

    if (jObj.has("gender"))
        gender = Gender.valueOf(jObj.getJSONObject("gender").getString("value"));

    if (jObj.has("mood"))
        mood = jObj.getJSONObject("mood").getString("value");

    if (jObj.has("lips"))
        lips = jObj.getJSONObject("lips").getString("value");

    if (jObj.has("age-est"))
        ageEst = jObj.getJSONObject("age-est").getInt("vaule");

    if (jObj.has("age-min"))
        ageMin = jObj.getJSONObject("age-min").getInt("vaule");

    if (jObj.has("age-max"))
        ageMax = jObj.getJSONObject("age-max").getInt("vaule");

    faceConfidence = jObj.getJSONObject("face").getInt("confidence");

    faceRect = new Rect(center, width, height);
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse account value.//from   w w  w  .j  a va 2s.co m
 * 
 * @param jsonNewAccount
 * @param acnt
 */
protected static void parseAccountValues(JSONObject jsonNewAccount, Account acnt) {
    JSONArray jsonPeriodBudgetList = jsonNewAccount.optJSONArray("periodBudget");
    JSONArray jsonPeriodValueList = jsonNewAccount.optJSONArray("periodValue");
    if (jsonPeriodBudgetList != null) {
        for (int j = 0; j < jsonPeriodBudgetList.length(); j++) {
            JSONObject jsonPeriodBudget = jsonPeriodBudgetList.getJSONObject(j);
            acnt.setBudget(jsonPeriodBudget.getString("periodId"), jsonPeriodBudget.getDouble("budget"));
        }
    }
    if (jsonPeriodValueList != null) {
        for (int j = 0; j < jsonPeriodValueList.length(); j++) {
            JSONObject jsonPeriodValue = jsonPeriodValueList.getJSONObject(j);
            acnt.setValue(jsonPeriodValue.getString("periodId"),
                    parseValue(jsonPeriodValue.optJSONObject("value")));

        }
    }
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse periods.//from   ww  w  . j  a  v  a 2  s.  c  o m
 * 
 * @param jsonList
 * @param periodList
 * @param book
 */
protected static void parsePeriods(JSONArray jsonList, List<Period> periodList, Book book) {
    for (int i = 0; i < jsonList.length(); i++) {
        JSONObject jsonPeriod = jsonList.getJSONObject(i);
        Period newPeriod = new Period(Formatter.parseDate(jsonPeriod.getString("date")));
        newPeriod.setId(jsonPeriod.getString("id"));
        newPeriod.setValue(parseValue(jsonPeriod.optJSONObject("value")));
        parseTransactions(jsonPeriod.optJSONArray("transactions"), newPeriod.getTransactions(), book);
        periodList.add(newPeriod);
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject toJSONObjectForCall(final UUID callId, final ShareOpenGraphContent content)
        throws JSONException {
    final ShareOpenGraphAction action = content.getAction();
    final ArrayList<NativeAppCallAttachmentStore.Attachment> attachments = new ArrayList<>();
    JSONObject actionJSON = OpenGraphJSONUtility.toJSONObject(action,
            new OpenGraphJSONUtility.PhotoJSONProcessor() {
                @Override//from  w w w.j  a v a  2 s  . c  om
                public JSONObject toJSONObject(SharePhoto photo) {
                    NativeAppCallAttachmentStore.Attachment attachment = getAttachment(callId, photo);

                    if (attachment == null) {
                        return null;
                    }

                    attachments.add(attachment);

                    JSONObject photoJSONObject = new JSONObject();
                    try {
                        photoJSONObject.put(NativeProtocol.IMAGE_URL_KEY, attachment.getAttachmentUrl());
                        if (photo.getUserGenerated()) {
                            photoJSONObject.put(NativeProtocol.IMAGE_USER_GENERATED_KEY, true);
                        }
                    } catch (JSONException e) {
                        throw new FacebookException("Unable to attach images", e);
                    }
                    return photoJSONObject;
                }
            });

    NativeAppCallAttachmentStore.addAttachments(attachments);
    // People and place tags must be moved from the share content to the open graph action
    if (content.getPlaceId() != null) {
        String placeTag = actionJSON.optString("place");

        // Only if the place tag is already empty or null replace with the id from the
        // share content
        if (Utility.isNullOrEmpty(placeTag)) {
            actionJSON.put("place", content.getPlaceId());
        }
    }

    if (content.getPeopleIds() != null) {
        JSONArray peopleTags = actionJSON.optJSONArray("tags");
        Set<String> peopleIdSet = peopleTags == null ? new HashSet<String>()
                : Utility.jsonArrayToSet(peopleTags);

        for (String peopleId : content.getPeopleIds()) {
            peopleIdSet.add(peopleId);
        }
        actionJSON.put("tags", new ArrayList<>(peopleIdSet));
    }

    return actionJSON;
}

From source file:com.phelps.liteweibo.model.weibo.GeoList.java

public static GeoList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from  www  .jav a 2  s  .  c om

    GeoList geoList = new GeoList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            geoList.Geos = new ArrayList<Geo>(length);
            for (int ix = 0; ix < length; ix++) {
                geoList.Geos.add(Geo.parse(jsonArray.optJSONObject(ix)));
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return geoList;
}