Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve another JSON object stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/*  w w  w . j  a va 2 s  . c o  m*/
 * @return the JSON object stored in the key, or null if the key doesn't exist
 */
public static JSONObject safeGetObject(JSONObject obj, String key) {
    if (obj == null || TextUtils.isEmpty(key))
        return null;
    if (obj.has(key)) {
        try {
            return obj.getJSONObject(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get JSONObject from key " + key, e);
        }
    }
    return null;
}

From source file:net.idlesoft.android.apps.github.activities.SingleActivityItem.java

private void loadActivityItemBox() {
    final TextView date = (TextView) findViewById(R.id.tv_activity_item_date);
    final ImageView gravatar = (ImageView) findViewById(R.id.iv_activity_item_gravatar);
    final ImageView icon = (ImageView) findViewById(R.id.iv_activity_item_icon);
    final TextView title_tv = (TextView) findViewById(R.id.tv_activity_item_title);

    try {//w w w.j a v  a 2s  . com
        final JSONObject entry = mJson;
        final JSONObject payload = entry.getJSONObject("payload");
        String end;
        final SimpleDateFormat dateFormat = new SimpleDateFormat(Hubroid.GITHUB_ISSUES_TIME_FORMAT);
        final Date item_time = dateFormat.parse(entry.getString("created_at"));
        final Date current_time = dateFormat.parse(dateFormat.format(new Date()));
        final long ms = current_time.getTime() - item_time.getTime();
        final long sec = ms / 1000;
        final long min = sec / 60;
        final long hour = min / 60;
        final long day = hour / 24;
        if (day > 0) {
            if (day == 1) {
                end = " day ago";
            } else {
                end = " days ago";
            }
            date.setText(day + end);
        } else if (hour > 0) {
            if (hour == 1) {
                end = " hour ago";
            } else {
                end = " hours ago";
            }
            date.setText(hour + end);
        } else if (min > 0) {
            if (min == 1) {
                end = " minute ago";
            } else {
                end = " minutes ago";
            }
            date.setText(min + end);
        } else {
            if (sec == 1) {
                end = " second ago";
            } else {
                end = " seconds ago";
            }
            date.setText(sec + end);
        }

        final String actor = entry.getString("actor");
        final String eventType = entry.getString("type");
        String title = actor + " did something...";
        gravatar.setImageBitmap(GravatarCache.getDipGravatar(GravatarCache.getGravatarID(actor), 30.0f,
                getResources().getDisplayMetrics().density));

        if (eventType.contains("PushEvent")) {
            icon.setImageResource(R.drawable.push);
            title = actor + " pushed to " + payload.getString("ref").split("/")[2] + " at "
                    + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("WatchEvent")) {
            final String action = payload.getString("action");
            if (action.equalsIgnoreCase("started")) {
                icon.setImageResource(R.drawable.watch_started);
            } else {
                icon.setImageResource(R.drawable.watch_stopped);
            }
            title = actor + " " + action + " watching " + entry.getJSONObject("repository").getString("owner")
                    + "/" + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("GistEvent")) {
            final String action = payload.getString("action");
            icon.setImageResource(R.drawable.gist);
            title = actor + " " + action + "d " + payload.getString("name");
        } else if (eventType.contains("ForkEvent")) {
            icon.setImageResource(R.drawable.fork);
            title = actor + " forked " + entry.getJSONObject("repository").getString("name") + "/"
                    + entry.getJSONObject("repository").getString("owner");
        } else if (eventType.contains("CommitCommentEvent")) {
            icon.setImageResource(R.drawable.comment);
            title = actor + " commented on " + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("ForkApplyEvent")) {
            icon.setImageResource(R.drawable.merge);
            title = actor + " applied fork commits to " + entry.getJSONObject("repository").getString("owner")
                    + "/" + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("FollowEvent")) {
            icon.setImageResource(R.drawable.follow);
            title = actor + " started following " + payload.getJSONObject("target").getString("login");
        } else if (eventType.contains("CreateEvent")) {
            icon.setImageResource(R.drawable.create);
            if (payload.getString("object").contains("repository")) {
                title = actor + " created repository " + payload.getString("name");
            } else if (payload.getString("object").contains("branch")) {
                title = actor + " created branch " + payload.getString("object_name") + " at "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            } else if (payload.getString("object").contains("tag")) {
                title = actor + " created tag " + payload.getString("object_name") + " at "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            }
        } else if (eventType.contains("IssuesEvent")) {
            if (payload.getString("action").equalsIgnoreCase("opened")) {
                icon.setImageResource(R.drawable.issues_open);
            } else {
                icon.setImageResource(R.drawable.issues_closed);
            }
            title = actor + " " + payload.getString("action") + " issue " + payload.getInt("number") + " on "
                    + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("DeleteEvent")) {
            icon.setImageResource(R.drawable.delete);
            if (payload.getString("object").contains("repository")) {
                title = actor + " deleted repository " + payload.getString("name");
            } else if (payload.getString("object").contains("branch")) {
                title = actor + " deleted branch " + payload.getString("object_name") + " at "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            } else if (payload.getString("object").contains("tag")) {
                title = actor + " deleted tag " + payload.getString("object_name") + " at "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            }
        } else if (eventType.contains("WikiEvent")) {
            icon.setImageResource(R.drawable.wiki);
            title = actor + " " + payload.getString("action") + " a page in the "
                    + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name") + " wiki";
        } else if (eventType.contains("DownloadEvent")) {
            icon.setImageResource(R.drawable.download);
            title = actor + " uploaded a file to " + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("PublicEvent")) {
            icon.setImageResource(R.drawable.opensource);
            title = actor + " open sourced " + entry.getJSONObject("repository").getString("name");
        } else if (eventType.contains("PullRequestEvent")) {
            final int number = (payload.get("pull_request") instanceof JSONObject)
                    ? payload.getJSONObject("pull_request").getInt("number")
                    : payload.getInt("number");
            if (payload.getString("action").equalsIgnoreCase("opened")) {
                icon.setImageResource(R.drawable.issues_open);
                title = actor + " opened pull request " + number + " on "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            } else if (payload.getString("action").equalsIgnoreCase("closed")) {
                icon.setImageResource(R.drawable.issues_closed);
                title = actor + " closed pull request " + number + " on "
                        + entry.getJSONObject("repository").getString("owner") + "/"
                        + entry.getJSONObject("repository").getString("name");
            }
        } else if (eventType.contains("MemberEvent")) {
            icon.setImageResource(R.drawable.follow);
            title = actor + " added " + payload.getString("member") + " to "
                    + entry.getJSONObject("repository").getString("owner") + "/"
                    + entry.getJSONObject("repository").getString("name");
        }

        title_tv.setText(title);

        gravatar.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                final Intent i = new Intent(SingleActivityItem.this, Profile.class);
                i.putExtra("username", actor);
                startActivity(i);
            }
        });

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

From source file:net.dv8tion.jda.core.handle.PresenceUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    //Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked.
    if (content.has("guild_id")) {
        final long guildId = content.getLong("guild_id");
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }//from  w  w  w  . ja  v a  2  s  . com

    JSONObject jsonUser = content.getJSONObject("user");
    final long userId = jsonUser.getLong("id");
    UserImpl user = (UserImpl) api.getUserMap().get(userId);

    //If we do know about the user, lets update the user's specific info.
    // Afterwards, we will see if we already have them cached in the specific guild
    // or Relation. If not, we'll cache the OnlineStatus and Game for later handling
    // unless OnlineStatus is OFFLINE, in which case we probably received this event
    // due to a User leaving a guild or no longer being a relation.
    if (user != null) {
        if (jsonUser.has("username")) {
            String name = jsonUser.getString("username");
            String discriminator = jsonUser.get("discriminator").toString();
            String avatarId = jsonUser.isNull("avatar") ? null : jsonUser.getString("avatar");

            if (!user.getName().equals(name)) {
                String oldUsername = user.getName();
                String oldDiscriminator = user.getDiscriminator();
                user.setName(name);
                user.setDiscriminator(discriminator);
                api.getEventManager().handle(
                        new UserNameUpdateEvent(api, responseNumber, user, oldUsername, oldDiscriminator));
            }
            String oldAvatar = user.getAvatarId();
            if (!(avatarId == null && oldAvatar == null) && !Objects.equals(avatarId, oldAvatar)) {
                String oldAvatarId = user.getAvatarId();
                user.setAvatarId(avatarId);
                api.getEventManager().handle(new UserAvatarUpdateEvent(api, responseNumber, user, oldAvatarId));
            }
        }

        //Now that we've update the User's info, lets see if we need to set the specific Presence information.
        // This is stored in the Member or Relation objects.
        String gameName = null;
        String gameUrl = null;
        Game.GameType type = null;
        if (!content.isNull("game") && !content.getJSONObject("game").isNull("name")) {
            gameName = content.getJSONObject("game").get("name").toString();
            gameUrl = (content.getJSONObject("game").isNull("url") ? null
                    : content.getJSONObject("game").get("url").toString());
            try {
                type = content.getJSONObject("game").isNull("type") ? Game.GameType.DEFAULT
                        : Game.GameType.fromKey(
                                Integer.parseInt(content.getJSONObject("game").get("type").toString()));
            } catch (NumberFormatException ex) {
                type = Game.GameType.DEFAULT;
            }
        }
        Game nextGame = (gameName == null ? null : new GameImpl(gameName, gameUrl, type));
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));

        //If we are in a Guild, then we will use Member.
        // If we aren't we'll be dealing with the Relation system.
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            MemberImpl member = (MemberImpl) guild.getMember(user);

            //If the Member is null, then User isn't in the Guild.
            //This is either because this PRESENCE_UPDATE was received before the GUILD_MEMBER_ADD event
            // or because a Member recently left and this PRESENCE_UPDATE came after the GUILD_MEMBER_REMOVE event.
            //If it is because a Member recently left, then the status should be OFFLINE. As such, we will ignore
            // the event if this is the case. If the status isn't OFFLINE, we will cache and use it when the
            // Member object is setup during GUILD_MEMBER_ADD
            if (member == null) {
                //Cache the presence and return to finish up.
                if (status != OnlineStatus.OFFLINE) {
                    guild.getCachedPresenceMap().put(userId, content);
                    return null;
                }
            } else {
                //The member is already cached, so modify the presence values and fire events as needed.
                if (!member.getOnlineStatus().equals(status)) {
                    OnlineStatus oldStatus = member.getOnlineStatus();
                    member.setOnlineStatus(status);
                    api.getEventManager().handle(
                            new UserOnlineStatusUpdateEvent(api, responseNumber, user, guild, oldStatus));
                }
                if (member.getGame() == null ? nextGame != null : !member.getGame().equals(nextGame)) {
                    Game oldGame = member.getGame();
                    member.setGame(nextGame);
                    api.getEventManager()
                            .handle(new UserGameUpdateEvent(api, responseNumber, user, guild, oldGame));
                }
            }
        } else {
            //In this case, this PRESENCE_UPDATE is for a Relation.

        }
    } else {
        //In this case, we don't have the User cached, which means that we can't update the User's information.
        // This is most likely because this PRESENCE_UPDATE came before the GUILD_MEMBER_ADD that would have added
        // this User to our User cache. Or, it could have come after a GUILD_MEMBER_REMOVE that caused the User
        // to be removed from JDA's central User cache because there were no more connected Guilds. If this is
        // the case, then the OnlineStatus will be OFFLINE and we can ignore this event.
        //Either way, we don't have the User cached so we need to cache the Presence information if
        // the OnlineStatus is not OFFLINE.

        //If the OnlineStatus is OFFLINE, ignore the event and return.
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
        if (status == OnlineStatus.OFFLINE)
            return null;

        //If this was for a Guild, cache it in the Guild for later use in GUILD_MEMBER_ADD
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            guild.getCachedPresenceMap().put(userId, content);
        } else {
            //cache in relationship stuff
        }
    }
    return null;
}

From source file:com.googlecode.goclipse.tooling.oracle.OraclePackageDescribeParser.java

protected ArrayList2<StructureElement> doParseJsonResult(String output) throws JSONException, CommonException {
    JSONObject jsonResult = new JSONObject(output);

    JSONObject describe = jsonResult.getJSONObject("describe");

    JSONObject packageObj = describe.getJSONObject("package");

    JSONArray members = getOptionalJSONArray(packageObj, "members");
    return parseElements(members, false);
}

From source file:cgeo.geocaching.connector.gc.GCParser.java

public static SearchResult searchByAddress(final String address, final CacheType cacheType,
        final boolean showCaptcha, RecaptchaReceiver recaptchaReceiver) {
    if (StringUtils.isBlank(address)) {
        Log.e("GCParser.searchByAddress: No address given");
        return null;
    }/*w  ww. j av a 2s .  c  o m*/
    try {
        final JSONObject response = Network.requestJSON("http://www.geocaching.com/api/geocode",
                new Parameters("q", address));
        if (response == null) {
            return null;
        }
        if (!StringUtils.equalsIgnoreCase(response.getString("status"), "success")) {
            return null;
        }
        if (!response.has("data")) {
            return null;
        }
        final JSONObject data = response.getJSONObject("data");
        if (data == null) {
            return null;
        }
        return searchByCoords(new Geopoint(data.getDouble("lat"), data.getDouble("lng")), cacheType,
                showCaptcha, recaptchaReceiver);
    } catch (final JSONException e) {
        Log.w("GCParser.searchByAddress", e);
    }

    return null;
}

From source file:pt.webdetails.cdb.query.AbstractQuery.java

@Override
public void fromJSON(JSONObject json) {
    String _id, _key, _group, _name;
    HashMap<String, Object> _properties = new HashMap<String, Object>();
    try {/*  www  .  j  av a2  s  .co m*/
        /* Load everything into temporary variables */
        _id = json.getString("guid");
        _key = json.getString("@rid");
        _group = json.getString("group");
        _name = json.getString("name");
        JSONObject props = json.getJSONObject("definition");
        for (String key : JSONObject.getNames(props)) {
            _properties.put(key, props.get(key));
        }
        /* Seems like we managed to safely load everything, so it's
         * now safe to copy all the values over to the object
         */
        id = _id;
        key = _key;
        group = _group;
        name = _name;
        properties = _properties;
    } catch (JSONException jse) {
        logger.error("Error while reading values from JSON", jse);
    }
}

From source file:com.att.api.dc.model.DCResponse.java

/**
 * Factory method for creating a DC response by parsing a JSON object.
 *
 * @param jobj JSON object to parse/*from  ww w  .j  a  v a 2 s  .  c o m*/
 * @return DC response
 */
public static DCResponse valueOf(JSONObject jobj) {
    DCResponse response = new DCResponse();

    // parse json
    JSONObject deviceInfo = jobj.getJSONObject("DeviceInfo");
    JSONObject deviceId = deviceInfo.getJSONObject("DeviceId");
    JSONObject capabilities = deviceInfo.getJSONObject("Capabilities");
    response.typeAllocationCode = deviceId.getString("TypeAllocationCode");

    response.name = capabilities.getString("Name");
    response.vendor = capabilities.getString("Vendor");
    response.model = capabilities.getString("Model");
    response.firmwareVersion = capabilities.getString("FirmwareVersion");
    response.uaProf = capabilities.getString("UaProf");

    final String mmsCapableStr = capabilities.getString("MmsCapable");
    response.mmsCapable = mmsCapableStr.equals("Y") ? true : false;

    final String assistedGpsStr = capabilities.getString("AssistedGps");
    response.assistedGps = assistedGpsStr.equals("Y") ? true : false;

    response.locationTechnology = capabilities.getString("LocationTechnology");
    response.deviceBrowser = capabilities.getString("DeviceBrowser");

    final String wapPushStr = capabilities.getString("WapPushCapable");
    response.wapPushCapable = wapPushStr.equals("Y") ? true : false;

    return response;
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleRequestEvent(JSONObject data) {
    try {//from w  w w .jav a 2s  .  co m
        // Get myOH unique request Id
        int requestId = data.getInt("id");
        logger.debug("Got request {}", requestId);
        // Get request path
        String requestPath = data.getString("path");
        // Get request method
        String requestMethod = data.getString("method");
        // Get request body
        String requestBody = data.getString("body");
        // Get JSONObject for request headers
        JSONObject requestHeadersJson = data.getJSONObject("headers");
        logger.debug(requestHeadersJson.toString());
        // Get JSONObject for request query parameters
        JSONObject requestQueryJson = data.getJSONObject("query");
        // Create URI builder with base request URI of openHAB and path from request
        String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
        @SuppressWarnings("unchecked")
        Iterator<String> queryIterator = requestQueryJson.keys();
        // Add query parameters to URI builder, if any
        newPath += "?";
        while (queryIterator.hasNext()) {
            String queryName = queryIterator.next();
            newPath += queryName;
            newPath += "=";
            newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
            if (queryIterator.hasNext())
                newPath += "&";
        }
        // Finally get the future request URI
        URI requestUri = new URI(newPath);
        // All preparations which are common for different methods are done
        // Now perform the request to openHAB
        // If method is GET
        logger.debug("Request method is " + requestMethod);
        Request request = jettyClient.newRequest(requestUri);
        setRequestHeaders(request, requestHeadersJson);
        request.header("X-Forwarded-Proto", "https");
        if (requestMethod.equals("GET")) {
            request.method(HttpMethod.GET);
        } else if (requestMethod.equals("POST")) {
            request.method(HttpMethod.POST);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else if (requestMethod.equals("PUT")) {
            request.method(HttpMethod.PUT);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else {
            // TODO: Reject unsupported methods
            logger.error("Unsupported request method " + requestMethod);
            return;
        }
        ResponseListener listener = new ResponseListener(requestId);
        request.onResponseHeaders(listener).onResponseContent(listener).onRequestFailure(listener)
                .send(listener);
        // If successfully submitted request to http client, add it to the list of currently
        // running requests to be able to cancel it if needed
        runningRequests.put(requestId, request);
    } catch (JSONException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
    }
}

From source file:app.com.example.android.sunshine.ForecastFragment.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from  w ww  . j a va 2  s  .c o  m*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

private JSONObject parseConfig(JSONArray data) throws JSONException {
    JSONObject pushConfig = data.getJSONObject(0);
    if (!pushConfig.isNull("android")) {
        final JSONObject android = pushConfig.getJSONObject("android");
        for (Iterator iterator = android.keys(); iterator.hasNext();) {
            String key = (String) iterator.next();
            pushConfig.put(key, android.get(key));
        }/*from   w  w w. j  av  a 2 s.  com*/

        pushConfig.remove("android");
    }
    return pushConfig;
}