Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:weathernotificationservice.wns.activities.MainActivity.java

public ParseResult parseLongTermJson(String result) {
    int i;// w ww.j  a  va 2  s. c o  m
    try {
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            if (longTermWeather == null) {
                longTermWeather = new ArrayList<>();
                longTermTodayWeather = new ArrayList<>();
                longTermTomorrowWeather = new ArrayList<>();
            }
            return ParseResult.CITY_NOT_FOUND;
        }

        longTermWeather = new ArrayList<>();
        longTermTodayWeather = new ArrayList<>();
        longTermTomorrowWeather = new ArrayList<>();

        JSONArray list = reader.getJSONArray("list");
        for (i = 0; i < list.length(); i++) {
            Weather weather = new Weather();

            JSONObject listItem = list.getJSONObject(i);
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));
            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            if (windObj != null) {
                weather.setWind(windObj.getString("speed"));
                weather.setWindDirectionDegree(windObj.getDouble("deg"));
            }
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";
            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);

            final String dateMsString = listItem.getString("dt") + "000";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(dateMsString));
            weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));

            Calendar today = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                longTermTodayWeather.add(weather);
            } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                longTermTomorrowWeather.add(weather);
            } else {
                longTermWeather.add(weather);
            }
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastLongterm", result);
        editor.commit();
    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:com.google.android.apps.muzei.api.internal.SourceState.java

public void readJson(JSONObject jsonObject) throws JSONException {
    JSONObject artworkJsonObject = jsonObject.optJSONObject("currentArtwork");
    if (artworkJsonObject != null) {
        mCurrentArtwork = Artwork.fromJson(artworkJsonObject);
    }//from  www . j a v a2s  .  c o m
    mDescription = jsonObject.optString("description");
    mWantsNetworkAvailable = jsonObject.optBoolean("wantsNetworkAvailable");
    mUserCommands.clear();
    JSONArray commandsSerialized = jsonObject.optJSONArray("userCommands");
    if (commandsSerialized != null && commandsSerialized.length() > 0) {
        int length = commandsSerialized.length();
        for (int i = 0; i < length; i++) {
            mUserCommands.add(UserCommand.deserialize(commandsSerialized.optString(i)));
        }
    }
}

From source file:com.vk.sdkweb.api.model.VKApiPhoto.java

/**
 * Fills a Photo instance from JSONObject.
 *//*  www  . ja va  2 s .  c  o  m*/
public VKApiPhoto parse(JSONObject from) {
    album_id = from.optInt("album_id");
    date = from.optLong("date");
    height = from.optInt("height");
    width = from.optInt("width");
    owner_id = from.optInt("owner_id");
    id = from.optInt("id");
    text = from.optString("text");
    access_key = from.optString("access_key");

    photo_75 = from.optString("photo_75");
    photo_130 = from.optString("photo_130");
    photo_604 = from.optString("photo_604");
    photo_807 = from.optString("photo_807");
    photo_1280 = from.optString("photo_1280");
    photo_2560 = from.optString("photo_2560");

    JSONObject likes = from.optJSONObject("likes");
    this.likes = ParseUtils.parseInt(likes, "count");
    this.user_likes = ParseUtils.parseBoolean(likes, "user_likes");
    comments = parseInt(from.optJSONObject("comments"), "count");
    tags = parseInt(from.optJSONObject("tags"), "count");
    can_comment = parseBoolean(from, "can_comment");

    src.setOriginalDimension(width, height);
    JSONArray photo_sizes = from.optJSONArray("sizes");
    if (photo_sizes != null) {
        src.fill(photo_sizes);
    } else {
        if (!TextUtils.isEmpty(photo_75)) {
            src.add(VKApiPhotoSize.create(photo_75, VKApiPhotoSize.S, width, height));
        }
        if (!TextUtils.isEmpty(photo_130)) {
            src.add(VKApiPhotoSize.create(photo_130, VKApiPhotoSize.M, width, height));
        }
        if (!TextUtils.isEmpty(photo_604)) {
            src.add(VKApiPhotoSize.create(photo_604, VKApiPhotoSize.X, width, height));
        }
        if (!TextUtils.isEmpty(photo_807)) {
            src.add(VKApiPhotoSize.create(photo_807, VKApiPhotoSize.Y, width, height));
        }
        if (!TextUtils.isEmpty(photo_1280)) {
            src.add(VKApiPhotoSize.create(photo_1280, VKApiPhotoSize.Z, width, height));
        }
        if (!TextUtils.isEmpty(photo_2560)) {
            src.add(VKApiPhotoSize.create(photo_2560, VKApiPhotoSize.W, width, height));
        }
        src.sort();
    }
    return this;
}

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

public Webservice(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // set the xml version
    super();/*  w w w. j a v a 2 s. c o  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 query
        if (!"request".equals(key) && !"root".equals(key) && !"showLoading".equals(key)
                && !"successActions".equals(key) && !"errorActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // try and build the query object
    JSONObject jsonQuery = jsonAction.optJSONObject("request");

    // check we got one
    if (jsonQuery != null) {
        // get the parameters                  
        ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
        String type = jsonQuery.optString("type");
        String url = jsonQuery.optString("url");
        String action = jsonQuery.optString("action");
        String body = jsonQuery.optString("body");
        String transform = jsonQuery.optString("transform");
        String root = jsonQuery.optString("root");
        ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
        // make the object
        _request = new Request(inputs, type, url, action, body, transform, root, outputs);
    }

    // look for showLoading
    _showLoading = jsonAction.optBoolean("showLoading");

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some
    if (jsonSuccessActions != null) {
        // instantiate our success actions collection
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
    }

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some
    if (jsonErrorActions != null) {
        // instantiate our error actions collection
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
    }

}

From source file:org.eclipse.orion.server.tests.servlets.git.GitLogTest.java

@Test
public void testRefPropertiesForCommits() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

        // save initial commit name
        JSONArray commitsArray = log(gitCommitUri);
        JSONObject initCommit = commitsArray.getJSONObject(0);
        String initCommitName = initCommit.getString(ProtocolConstants.KEY_NAME);
        String initCommitLocation = initCommit.getString(ProtocolConstants.KEY_LOCATION);

        // modify
        JSONObject testTxt = getChild(project, "test.txt");
        modifyFile(testTxt, "test.txt change");
        addFile(testTxt);/*from  ww w  .  j  a va  2  s . co m*/

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        String logUri = initCommitLocation.replace(initCommitName, initCommitName + ".." + initCommitName);
        // git log for {initial commit}..{initial commit}
        // both fromRef and toRef shouldn't exist, as commit ref doesn't point to a branch
        JSONObject log = logObject(logUri);

        JSONObject fromRef = log.optJSONObject(GitConstants.KEY_LOG_FROM_REF);
        JSONObject toRef = log.optJSONObject(GitConstants.KEY_LOG_TO_REF);

        assertNull(fromRef);
        assertNull(toRef);
    }
}

From source file:com.example.protocol.STATUSES.java

public void fromJson(JSONObject jsonObject) throws JSONException {
    if (null == jsonObject) {
        return;// w w w.j av a 2  s .  co  m
    }

    JSONArray subItemArray;

    this.comments_count = jsonObject.optInt("comments_count");

    this.text = jsonObject.optString("text");

    this.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    this.truncated = jsonObject.optBoolean("truncated");

    this.bmiddle_pic = jsonObject.optString("bmiddle_pic");

    this.thumbnail_pic = jsonObject.optString("thumbnail_pic");

    this.source = jsonObject.optString("source");

    this.favorited = jsonObject.optBoolean("favorited");

    this.original_pic = jsonObject.optString("original_pic");

    this.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");

    this.reposts_count = jsonObject.optInt("reposts_count");

    this.created_at = jsonObject.optString("created_at");

    this.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");

    subItemArray = jsonObject.optJSONArray("annotations");
    if (null != subItemArray) {
        for (int i = 0; i < subItemArray.length(); i++) {
            String subItemObject = subItemArray.optString(i);
            String subItem = subItemObject;
            this.annotations.add(subItem);
        }
    }

    this.mid = jsonObject.optString("mid");
    USER user = new USER();
    user.fromJson(jsonObject.optJSONObject("user"));
    this.user = user;
    return;
}

From source file:edu.stanford.junction.api.activity.ActivityScript.java

public ActivityScript(JSONObject json) {
    mJSON = json;//from   w  ww  .  j a va 2s.  c om

    // TODO: Deprecate. These should not be in the activityDescription.
    // preferred
    if (json.has("switchboard")) {
        host = json.optString("switchboard");
    }
    // deprecated
    else if (json.has("host")) {
        host = json.optString("host");
    }

    // TODO: rename this field
    if (json.has(("ad"))) {
        activityID = json.optString("ad");
    }

    if (json.has("friendlyName")) {
        friendlyName = json.optString("friendlyName");
    }

    if (json.has("sessionID")) {
        sessionID = json.optString("sessionID");
    }

    ////////////////////////////////////////////
    roleSpecs = json.optJSONObject("roles");

}

From source file:edu.stanford.junction.api.activity.ActivityScript.java

public JSONObject getRolePlatform(String role, String platform) {
    try {/*w w w .j a v a2s .  c o m*/
        JSONObject spec = getRoleSpec(role);
        if (spec == null)
            return null;
        spec = spec.optJSONObject("platforms");

        if (spec == null)
            return null;
        if (spec.has(platform)) {
            return spec.getJSONObject(platform);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.vk.sdkweb.api.model.VKApiPost.java

/**
 * Fills a Post instance from JSONObject.
 *//*from   w  w w.  ja v a2  s  .  co  m*/
public VKApiPost parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    to_id = source.optInt("to_id");
    from_id = source.optInt("from_id");
    date = source.optLong("date");
    text = source.optString("text");
    reply_owner_id = source.optInt("reply_owner_id");
    reply_post_id = source.optInt("reply_post_id");
    friends_only = ParseUtils.parseBoolean(source, "friends_only");
    JSONObject comments = source.optJSONObject("comments");
    if (comments != null) {
        comments_count = comments.optInt("count");
        can_post_comment = ParseUtils.parseBoolean(comments, "can_post");
    }
    JSONObject likes = source.optJSONObject("likes");
    if (likes != null) {
        likes_count = likes.optInt("count");
        user_likes = ParseUtils.parseBoolean(likes, "user_likes");
        can_like = ParseUtils.parseBoolean(likes, "can_like");
        can_publish = ParseUtils.parseBoolean(likes, "can_publish");
    }
    JSONObject reposts = source.optJSONObject("reposts");
    if (reposts != null) {
        reposts_count = reposts.optInt("count");
        user_reposted = ParseUtils.parseBoolean(reposts, "user_reposted");
    }
    post_type = source.optString("post_type");
    attachments.fill(source.optJSONArray("attachments"));
    JSONObject geo = source.optJSONObject("geo");
    if (geo != null) {
        this.geo = new VKApiPlace().parse(geo);
    }
    signer_id = source.optInt("signer_id");
    copy_history = new VKList<VKApiPost>(source.optJSONArray("copy_history"), VKApiPost.class);
    return this;
}

From source file:fi.harism.lucidchat.api.ChatConnection.java

/**
 * Handle server event messages.//  w w  w  .  j av a  2s . c  o  m
 */
private void handleEvent(String message) {
    try {
        // We receive always JSON messages.
        JSONObject json = new JSONObject(message);
        // Get event type from JSON.
        String event = json.optString("event");

        // Handle session_created event.
        if (event.equals("session_created")) {

            // Here we expect that server sends user_auth only when new
            // session is created. In case where old session was continues
            // user_auth ought not to be present.
            if (!json.has("user_auth")) {
                // Notify server about connection.
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session resumed userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
            } else {
                // New session was created.
                mUserId = json.getString("user_id");
                mUserAuth = json.getString("user_auth");
                mSessionId = json.getString("session_id");
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session created userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
                // If autojoin is enabled send join message.
                if (mAutojoin) {
                    sendJoinChannel(NINCHAT_LOUNGE);
                }
            }
        }

        // Handle user_updated and user_found events.
        if (event.equals("user_updated") || event.equals("user_found")) {
            String userId = json.getString("user_id");
            // If update was sent for ourself.
            if (userId.equals(mUserId)) {
                // We do nothing on updates sent to self at the moment.
            } else {
                // Notify observer about user updated event.
                JSONObject userAttrs = json.getJSONObject("user_attrs");
                String name = userAttrs.optString("name");
                String realName = userAttrs.optString("realname");
                boolean connected = userAttrs.optBoolean("connected");
                mObserver.onUserUpdated(new User(userId, name, realName, connected));
            }
        }

        // Handle channel_updated event.
        if (event.equals("channel_updated")) {
            String channelId = json.getString("channel_id");
            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.optString("name");
            String topic = channelAttrs.optString("topic");
            mObserver.onChannelUpdated(new Channel(channelId, name, topic));
        }

        // Handle search_results event.
        if (event.equals("search_results")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Search results event"));
            Vector<Channel> channelList = new Vector<Channel>();
            // Parse channels from search results.
            JSONObject channels = json.optJSONObject("channels");
            if (channels != null) {
                JSONArray names = channels.names();
                for (int i = 0; i < names.length(); ++i) {
                    String channelId = names.getString(i);
                    JSONObject channelAttrs = channels.getJSONObject(channelId).getJSONObject("channel_attrs");
                    String name = channelAttrs.optString("name");
                    String topic = channelAttrs.optString("topic");
                    channelList.add(new Channel(channelId, name, topic));
                }
            }
            // Parse users from search results.
            Vector<User> userList = new Vector<User>();
            JSONObject users = json.optJSONObject("users");
            if (users != null) {
                JSONArray names = users.names();
                for (int i = 0; i < names.length(); ++i) {
                    String userId = names.getString(i);
                    if (!userId.equals(mUserId)) {
                        JSONObject user = users.getJSONObject(userId);
                        String name = user.optString("name");
                        String realName = user.optString("realname");
                        boolean connected = user.optBoolean("connected");
                        userList.add(new User(userId, name, realName, connected));
                    }
                }
            }
            mObserver.onSearchResults(channelList, userList);
        }

        // Handle channel_joined event.
        if (event.equals("channel_joined")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Channel joined event"));

            String channelId = json.getString("channel_id");
            Vector<User> userList = new Vector<User>();
            JSONObject channelMembers = json.getJSONObject("channel_members");
            JSONArray names = channelMembers.names();
            for (int i = 0; i < names.length(); ++i) {
                String userId = names.getString(i);
                JSONObject userAttrs = channelMembers.getJSONObject(userId).getJSONObject("user_attrs");
                if (!userId.equals(mUserId)) {
                    String name = userAttrs.optString("name");
                    String realName = userAttrs.optString("realname");
                    boolean connected = userAttrs.optBoolean("connected");
                    userList.add(new User(userId, name, realName, connected));
                }
            }

            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.getString("name");
            String topic = channelAttrs.getString("topic");

            mObserver.onChannelJoined(new Channel(channelId, name, topic), userList);
        }

        // Message receiving happens with 2 callbacks. First
        // message_received is sent from server and then an empty JSON with
        // message only.
        if (event.equals("message_received")) {
            // Check message_type. We handle only text messages.
            if (json.optString("message_type").equals("ninchat.com/text")) {
                mMessage = json;
            }
            if (json.optString("message_type").equals("ninchat.com/info")) {
                mMessage = json;
            }
        }
        // Second part of text message receiving.
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/text")
                && json.has("text")) {
            // Message time is in seconds after epoch.
            long messageTime = mMessage.getLong("message_time") * 1000;
            String messageUserName = mMessage.getString("message_user_name");
            String channelId = mMessage.optString("channel_id");
            String userId = mMessage.optString("user_id");
            String text = json.getString("text");
            mMessage = null;

            // If channel_id exists notify observer about channel message.
            if (channelId.length() > 0) {
                mObserver.onChannelMessage(channelId,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
            // If user_id exists notify observer about private message.
            if (userId.length() > 0) {
                User user = new User(userId, messageUserName, "", true);
                mObserver.onUserMessage(user,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
        }
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/info")
                && json.has("info")) {
            String info = json.getString("info");
            if (info.equals("join")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoJoin(channelId, userId, userName);
            }
            if (info.equals("part")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoPart(channelId, userId, userName);
            }

            mMessage = null;
        }

        // Handle channel_parted event.
        if (event.equals("channel_parted")) {
            String channelId = json.getString("channel_id");
            mObserver.onChannelParted(channelId);
        }

        // Handle channel_member_joined.
        if (event.equals("channel_member_joined")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            JSONObject userAttrs = json.getJSONObject("user_attrs");
            String name = userAttrs.getString("name");
            String realname = userAttrs.optString("realname");
            boolean connected = userAttrs.optBoolean("connected");
            mObserver.onUserJoin(channelId, new User(userId, name, realname, connected));
        }

        // Handle channel_member_parted.
        if (event.equals("channel_member_parted")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            mObserver.onUserPart(channelId, userId);
        }

        // Handle second phase of delete_user.
        if (event.equals("user_deleted")) {
            mWSC.disconnect();
        }

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