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:de.jaetzold.philips.hue.HueBridge.java

List<JSONObject> checkedSuccessRequest(HueBridgeComm.RM method, String userPath, Object json) {
    final List<JSONObject> response = request(method, userPath, json);
    for (JSONObject entry : response) {
        if (!entry.has("success")) {
            throw new HueCommException(entry.getJSONObject("error"));
        }/*from ww  w  . j a  v  a 2 s  . c o m*/
    }
    return response;
}

From source file:com.norman0406.slimgress.API.Item.ItemPowerCube.java

public ItemPowerCube(JSONArray json) throws JSONException {
    super(ItemType.PowerCube, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject powerCube = item.getJSONObject("powerCube");

    mEnergy = powerCube.getInt("energy");
}

From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java

public ODocument createDocument(String baseClass, JSONObject json) {
    ODocument doc = new ODocument(baseClass);
    @SuppressWarnings("unchecked")
    Iterator<String> fields = json.keys();
    while (fields.hasNext()) {
        String field = fields.next();
        if (field.equals("key")) {
            continue;
        }//from  w  ww  . j  av  a  2s .  c o m

        try {
            Object value = json.get(field);
            if (value instanceof JSONObject) {

                doc.field(field, createDocument(baseClass + "_" + field, (JSONObject) value));

                JSONObject obj = json.getJSONObject(field);
                logger.debug("obj:" + obj.toString(JSON_INDENT));
            } else {
                doc.field(field, value);
            }

        } catch (JSONException e) {
            logger.error(e);
        }
    }

    return doc;
}

From source file:de.btobastian.javacord.utils.handler.message.MessageReactionAddHandler.java

@Override
public void handle(JSONObject packet) {
    String userId = packet.getString("user_id");
    String messageId = packet.getString("message_id");

    JSONObject emoji = packet.getJSONObject("emoji");
    boolean isCustomEmoji = !emoji.isNull("id");

    Message message = api.getMessageById(messageId);
    if (message == null) {
        return;//from   www  . j a v a  2s.  c o m
    }

    Reaction reaction = null;
    if (isCustomEmoji) {
        String emojiId = emoji.getString("id");
        if (message.isPrivateMessage()) {
            // Private messages with custom emoji? Maybe with Nitro, but there's no documentation so far.
            return;
        }
        CustomEmoji customEmoji = message.getChannelReceiver().getServer().getCustomEmojiById(emojiId);
        if (customEmoji == null) {
            // We don't know this emoji
            return;
        }
        reaction = ((ImplMessage) message).addCustomEmojiReactionToCache(customEmoji,
                api.getYourself().getId().equals(userId));
    } else {
        reaction = ((ImplMessage) message).addUnicodeReactionToCache(emoji.getString("name"),
                api.getYourself().getId().equals(userId));
    }

    if (reaction != null) {
        final User user = api.getCachedUserById(userId);
        if (user != null) {
            final Reaction reactionFinal = reaction;
            listenerExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    List<ReactionAddListener> listeners = api.getListeners(ReactionAddListener.class);
                    synchronized (listeners) {
                        for (ReactionAddListener listener : listeners) {
                            try {
                                listener.onReactionAdd(api, reactionFinal, user);
                            } catch (Throwable t) {
                                logger.warn("Uncaught exception in ReactionAddListener!", t);
                            }
                        }
                    }
                }
            });
        }
    }
}

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

private Long handleDefaultMessage(JSONObject content) {
    Message message;//from  w ww  .  j  av a 2  s  . c o  m
    try {
        message = api.getEntityBuilder().createMessage(content, true);
    } catch (IllegalArgumentException e) {
        switch (e.getMessage()) {
        case EntityBuilder.MISSING_CHANNEL: {
            final long channelId = content.getLong("channel_id");
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug("Received a message for a channel that JDA does not currently have cached");
            return null;
        }
        case EntityBuilder.MISSING_USER: {
            final long authorId = content.getJSONObject("author").getLong("id");
            api.getEventCache().cache(EventCache.Type.USER, authorId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug("Received a message for a user that JDA does not currently have cached");
            return null;
        }
        default:
            throw e;
        }
    }

    switch (message.getChannelType()) {
    case TEXT: {
        TextChannelImpl channel = (TextChannelImpl) message.getTextChannel();
        if (api.getGuildLock().isLocked(channel.getGuild().getIdLong())) {
            return channel.getGuild().getIdLong();
        }
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new GuildMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    case PRIVATE: {
        PrivateChannelImpl channel = (PrivateChannelImpl) message.getPrivateChannel();
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new PrivateMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    case GROUP: {
        GroupImpl channel = (GroupImpl) message.getGroup();
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new GroupMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    default:
        WebSocketClient.LOG
                .warn("Received a MESSAGE_CREATE with a unknown MessageChannel ChannelType. JSON: " + content);
        return null;
    }

    //Combo event
    api.getEventManager().handle(new MessageReceivedEvent(api, responseNumber, message));

    //        //searching for invites
    //        Matcher matcher = invitePattern.matcher(message.getContent());
    //        while (matcher.find())
    //        {
    //            InviteUtil.Invite invite = InviteUtil.resolve(matcher.group(1));
    //            if (invite != null)
    //            {
    //                api.getEventManager().handle(
    //                        new InviteReceivedEvent(
    //                                api, responseNumber,
    //                                message,invite));
    //            }
    //        }
    return null;
}

From source file:com.lge.helloFriendsCamera.MainActivity.java

private void handleFinishTakePicture(String response) {
    //Finish take picture, then show toast and close session
    String fileUrl = null;//  w w  w  .  j a  v  a2s  .co  m
    try {
        JSONObject jObject = new JSONObject((String) response);

        if (jObject.has(OSCParameterNameMapper.RESULTS)) {
            JSONObject results = jObject.getJSONObject(OSCParameterNameMapper.RESULTS);

            fileUrl = results.getString(OSCParameterNameMapper.FILEURL);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (fileUrl != null) {
        Toast.makeText(mContext, "Picture " + fileUrl + " is taken", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(mContext, "[Error] Take picture response Error", Toast.LENGTH_LONG).show();
    }
}

From source file:com.foxykeep.datadroidpoc.data.factory.PhoneDeleteFactory.java

public static long[] parseResult(String wsResponse) throws DataException {

    long[] deletedPhoneIdArray = null;

    try {/*from  w  w  w .jav a  2 s .  c  o  m*/
        JSONObject parser = new JSONObject(wsResponse);
        JSONObject jsonRoot = parser.getJSONObject(JSONTag.CRUD_PHONE_DELETE_ELEM_PHONES);
        JSONArray jsonPhoneArray = jsonRoot.getJSONArray(JSONTag.CRUD_PHONE_DELETE_ELEM_PHONE);
        int size = jsonPhoneArray.length();

        deletedPhoneIdArray = new long[size];

        for (int i = 0; i < size; i++) {
            deletedPhoneIdArray[i] = jsonPhoneArray.getJSONObject(i).getLong(JSONTag.CRUD_PHONE_DELETE_ELEM_ID);
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        throw new DataException(e);
    }

    return deletedPhoneIdArray;
}

From source file:com.eventattend.portal.bl.FaceBookBL.java

private FaceBookDTO getUserDetails(JSONObject jsonObject, FaceBookDTO faceBookDTO) {
    JSONArray jsonArray = null;//  w  w w  .ja v a2 s  .co m
    JSONObject jsonObjectLocation = null;
    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    try {

        if (jsonObject != null) {
            System.out.println("UId=> " + jsonObject.getString("uid"));
            if (jsonObject.getString("profile_url") != null) {
                faceBookDTO.setProfileUrl(jsonObject.getString("profile_url"));
                System.out.println("PROFILE_URL=> " + jsonObject.getString("profile_url"));
            }
            if (jsonObject.getString("name") != null) {
                System.out.println("Name=> " + jsonObject.getString("name"));
                faceBookDTO.setName(jsonObject.getString("name"));
            }
            if (jsonObject.getString("first_name") != null) {
                System.out.println("First Name=> " + jsonObject.getString("first_name"));
            }
            if (jsonObject.getString("last_name") != null) {
                System.out.println("Last Name=> " + jsonObject.getString("last_name"));
            }
            if (jsonObject.getString("birthday") != null
                    && (!jsonObject.getString("birthday").equals("null"))) {
                System.out.println("BIRTHDAY=> " + jsonObject.getString("birthday"));
            }

            if (jsonObject.getString("about_me") != null
                    && (!jsonObject.getString("about_me").equals("null"))) {
                System.out.println("About Me=> " + jsonObject.getString("about_me"));
            }

            if (jsonObject.getString("movies") != null && (!jsonObject.getString("movies").equals("null"))) {
                System.out.println("MOVIES=> " + jsonObject.getString("movies"));
            }
            if (jsonObject.getString("status") != null && (!jsonObject.getString("status").equals("null"))) {
                System.out.println("Status=> " + jsonObject.getString("status"));
            }
            if (jsonObject.getString("relationship_status") != null) {
                System.out.println("RELATIONSHIP_STATUS=> " + jsonObject.getString("relationship_status"));
            }
            if (jsonObject.getString("locale") != null) {
                System.out.println("LOCALE=> " + jsonObject.getString("locale"));
            }
            if (jsonObject.getString("wall_count") != null) {
                System.out.println("WALL_COUNT=> " + jsonObject.getString("wall_count"));
            }
            if (jsonObject.getString("quotes") != null) {
                System.out.println("QUOTES=> " + jsonObject.getString("quotes"));
            }
            if (jsonObject.getString("pic") != null) {
                System.out.println("PIC=> " + jsonObject.getString("pic"));
                faceBookDTO.setProfileImg(jsonObject.getString("pic"));
            }
            if (jsonObject.getString("pic_big") != null) {
                System.out.println("PIC_BIG=> " + jsonObject.getString("pic_big"));
                faceBookDTO.setProfileBigImg(jsonObject.getString("pic_big"));
            }
            if (jsonObject.getString("activities") != null) {
                System.out.println("ACTIVITIES=> " + jsonObject.getString("activities"));
            }
            if (jsonObject.getString("hometown_location") != null) {
                System.out.println("HOMETOWN_LOCATION=> " + jsonObject.getString("hometown_location"));
            }

            if (jsonObject.getString("hs_info") != null) {
                System.out.println("hs_info=> " + jsonObject.getString("hs_info"));
            }
            if (jsonObject.getString("education_history") != null) {
                String edu = jsonObject.getString("education_history");
                Collection coll = new ArrayList();
                JSONObject myString = new JSONObject().put(edu, coll);

                System.out.println("EDUCATION_HISTORY=> " + jsonObject.getString("education_history"));

            }
            if (jsonObject.getString("work_history") != null) {
                System.out.println("WORK_HISTORY=> " + jsonObject.getString("work_history"));
            }
            if (jsonObject.getString("affiliations") != null) {
                System.out.println("WORK_HISTORY=> " + jsonObject.getString("affiliations"));
            }
            if (jsonObject.getString("email_hashes") != null) {
                System.out.println("EMAIL_HASHES=> " + jsonObject.getString("email_hashes"));
            }
            if (jsonObject.getString("interests") != null) {
                System.out.println("INTERESTS=> " + jsonObject.getString("interests"));
            }

            if (jsonObject.getString("current_location") != null) {
                if (!jsonObject.getString("current_location").equals("null")) {
                    jsonObjectLocation = jsonObject.getJSONObject("current_location");
                    //         System.out.println("ObjectLocation=> "+jsonObjectLocation);

                } else {

                }
            } else {

            }

        }

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

From source file:com.eventattend.portal.bl.FaceBookBL.java

private ProfileDTO getUserData(JSONObject jsonObject) {
    JSONArray jsonArray = null;//from  w w w .ja va  2  s  . c  om
    JSONObject jsonObjectLocation = null;
    ProfileDTO profileDTO = null;

    try {
        if (jsonObject != null) {

            profileDTO = new ProfileDTO();

            profileDTO.setProfileId(jsonObject.getString("uid"));
            profileDTO.setFirstName(jsonObject.getString("first_name"));
            profileDTO.setLastName(jsonObject.getString("last_name"));
            profileDTO.setFaceBookImgUrl(jsonObject.getString("pic"));
            if (jsonObject.getString("current_location") != null) {
                if (!jsonObject.getString("current_location").equals("null")) {
                    jsonObjectLocation = jsonObject.getJSONObject("current_location");
                    //profileDTO.setLocation(getLocation(jsonObjectLocation));
                } else {
                    //profileDTO.setLocation("");
                }
            } else {
                //profileDTO.setLocation("");
            }
            //profileDTO.setFaceBookId(jsonObject.getString("profile_url"));
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return profileDTO;
}

From source file:bhaskarandroidnannodegree.popularmoviesstage1.asynctasks.FetchTrailReview.java

/**
 * Take the String representing the complete movie list in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p>/*from w  ww  . j av  a2  s  .c  o m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getMovieDataFromJson(String movieJsonStr) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String NAME = "name";
    final String SIZE = "size";
    final String SOURCE = "source";
    final String TYPE = "type";
    final String REVIEW_ID = "id";
    final String GENRE_ID = "id";
    final String AUTHOR = "author";
    final String CONTENT = "content";
    final String URL = "url";
    final String TOTAL_PAGES_REVIEWS = "total_pages";
    final String TOTAL_RESULTS_REVIEWS = "total_results";
    final String PAGE = "page";
    final String MOVIE_ID = "id";

    final String RESULT1 = "trailers";
    final String RESULT2 = "reviews";
    final String RESULT3 = "genres";
    final String YOUTUBE = "youtube";

    try {
        JSONObject movieJson = new JSONObject(movieJsonStr);
        JSONArray movieArrayTrailer = movieJson.getJSONObject(RESULT1).getJSONArray(YOUTUBE);
        JSONObject movieArrayReviews = movieJson.getJSONObject(RESULT2);
        JSONArray movieArrayGenres = movieJson.getJSONArray(RESULT3);

        String movie_id = movieJson.getString(MOVIE_ID);

        for (int i = 0; i < movieArrayTrailer.length(); i++) {

            JSONObject trailerInfo = movieArrayTrailer.getJSONObject(i);

            String name;
            String size;
            String source;
            String type;
            name = trailerInfo.getString(NAME);
            size = trailerInfo.getString(SIZE);
            source = trailerInfo.getString(SOURCE);
            type = trailerInfo.getString(TYPE);

            TrailerInfo trailer = new TrailerInfo();
            trailer.setName(name);
            trailer.setSize(size);
            trailer.setSource(source);
            trailer.setType(type);

            listTrailers.add(trailer);

        }

        String page = movieArrayReviews.getString(PAGE);
        String total_page = movieArrayReviews.getString(TOTAL_PAGES_REVIEWS);
        String total_results = movieArrayReviews.getString(TOTAL_RESULTS_REVIEWS);

        JSONArray reviews = movieArrayReviews.getJSONArray("results");

        for (int j = 0; j < reviews.length(); j++) {

            JSONObject reviewsInfo = reviews.getJSONObject(j);

            String id;
            String author;
            String content;
            String url;
            id = reviewsInfo.getString(REVIEW_ID);
            author = reviewsInfo.getString(AUTHOR);
            content = reviewsInfo.getString(CONTENT);
            url = reviewsInfo.getString(URL);

            MovieReview review = new MovieReview();
            review.setId(id);
            review.setAuthor(author);
            review.setContent(content);
            review.setUrl(url);

            listMovieReviews.add(review);
        }

        for (int i = 0; i < movieArrayGenres.length(); i++) {

            JSONObject gen = movieArrayGenres.getJSONObject(i);
            String genre_id = gen.getString(GENRE_ID);
            String name = gen.getString(NAME);

        }

    } catch (JSONException e) {
        //Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}