Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key, String defaultValue) 

Source Link

Document

Get an optional string associated with a key.

Usage

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

public static User parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from  w  ww . j av a  2  s.  c om*/

    User user = new User();
    user.id = jsonObject.optString("id", "");
    user.idstr = jsonObject.optString("idstr", "");
    user.screen_name = jsonObject.optString("screen_name", "");
    user.name = jsonObject.optString("name", "");
    user.province = jsonObject.optInt("province", -1);
    user.city = jsonObject.optInt("city", -1);
    user.location = jsonObject.optString("location", "");
    user.description = jsonObject.optString("description", "");
    user.url = jsonObject.optString("url", "");
    user.profile_image_url = jsonObject.optString("profile_image_url", "");
    user.profile_url = jsonObject.optString("profile_url", "");
    user.domain = jsonObject.optString("domain", "");
    user.weihao = jsonObject.optString("weihao", "");
    user.gender = jsonObject.optString("gender", "");
    user.followers_count = jsonObject.optInt("followers_count", 0);
    user.friends_count = jsonObject.optInt("friends_count", 0);
    user.statuses_count = jsonObject.optInt("statuses_count", 0);
    user.favourites_count = jsonObject.optInt("favourites_count", 0);
    user.created_at = jsonObject.optString("created_at", "");
    user.following = jsonObject.optBoolean("following", false);
    user.allow_all_act_msg = jsonObject.optBoolean("allow_all_act_msg", false);
    user.geo_enabled = jsonObject.optBoolean("geo_enabled", false);
    user.verified = jsonObject.optBoolean("verified", false);
    user.verified_type = jsonObject.optInt("verified_type", -1);
    user.remark = jsonObject.optString("remark", "");
    //user.status             = jsonObject.optString("status", ""); // XXX: NO Need ?
    user.allow_all_comment = jsonObject.optBoolean("allow_all_comment", true);
    user.avatar_large = jsonObject.optString("avatar_large", "");
    user.avatar_hd = jsonObject.optString("avatar_hd", "");
    user.verified_reason = jsonObject.optString("verified_reason", "");
    user.follow_me = jsonObject.optBoolean("follow_me", false);
    user.online_status = jsonObject.optInt("online_status", 0);
    user.bi_followers_count = jsonObject.optInt("bi_followers_count", 0);
    user.lang = jsonObject.optString("lang", "");

    // ???OpenAPI ??
    user.star = jsonObject.optString("star", "");
    user.mbtype = jsonObject.optString("mbtype", "");
    user.mbrank = jsonObject.optString("mbrank", "");
    user.block_word = jsonObject.optString("block_word", "");

    return user;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.AddPlaylistResponse.java

@Override
public AddPlaylistResponse fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        mId = jsonObject.optString("id", null);
        mTitle = jsonObject.optString("title", null);
        mSuccess = jsonObject.optBoolean("success");
    }//w w  w  .j  av  a2 s .c  o  m

    // return this object to allow chaining
    return this;
}

From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java

public static List<TranslationInfo> toTranslationList(JSONArray jsonArray) throws Exception {
    final int length = jsonArray.length();
    final List<TranslationInfo> translations = new ArrayList<TranslationInfo>(length);
    for (int i = 0; i < length; ++i) {
        final JSONObject translationObject = jsonArray.getJSONObject(i);
        final String name = translationObject.getString("name");
        final String shortName = translationObject.getString("shortName");
        final String language = translationObject.getString("language");
        final String blobKey = translationObject.optString("blobKey", null);
        final int size = translationObject.getInt("size");
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(shortName) || TextUtils.isEmpty(language)
                || size <= 0) {//from   w  w w.j av a 2  s.c o m
            throw new Exception("Illegal translation info.");
        }
        translations.add(new TranslationInfo(name, shortName, language, blobKey, size));
    }
    return translations;
}

From source file:io.s4.client.Driver.java

/**
 * Establish a connection to the adapter. Upon success, this enables the
 * client to send and receive events. The client must first be initialized.
 * Otherwise, this operation will fail.//from w w w  .  j a va  2  s .  co  m
 * 
 * @see #init()
 * 
 * @return true if and only if a connection was successfully established.
 * @throws IOException
 *             if the underlying TCP/IP socket throws an exception.
 */
public boolean connect() throws IOException {
    if (!state.isInitialized()) {
        // must first be initialized
        if (debug) {
            System.err.println("Not initialized.");
        }
        return false;
    } else if (state.isConnected()) {
        // nothing to do if already connected.
        return true;
    }

    String message = null;

    try {
        // constructing connect message
        JSONObject json = new JSONObject();

        json.put("uuid", uuid);
        json.put("readMode", readMode.toString());
        json.put("writeMode", writeMode.toString());

        if (readInclude != null) {
            // stream inclusion
            json.put("readInclude", new JSONArray(readInclude));
        }

        if (readExclude != null) {
            // stream exclusion
            json.put("readExclude", new JSONArray(readExclude));
        }

        message = json.toString();

    } catch (JSONException e) {
        if (debug) {
            System.err.println("error constructing connect message: " + e);
        }
        return false;
    }

    try {
        // send the message
        this.sock = new Socket(hostname, port);
        this.io = new ByteArrayIOChannel(sock);

        io.send(message.getBytes());

        // get a response
        byte[] b = io.recv();

        if (b == null || b.length == 0) {
            if (debug) {
                System.err.println("empty response from adapter during connect.");
            }
            return false;
        }

        String response = new String(b);

        JSONObject json = new JSONObject(response);
        String s = json.optString("status", "unknown");

        // does it look OK?
        if (s.equalsIgnoreCase("ok")) {
            // done connecting
            state = State.Connected;
            return true;
        } else if (s.equalsIgnoreCase("failed")) {
            // server has failed the connect attempt
            if (debug) {
                System.err.println("connect failed by adapter. reason: " + json.optString("reason", "unknown"));
            }
            return false;
        } else {
            // unknown response.
            if (debug) {
                System.err.println("connect failed by adapter. unrecongnized response: " + response);
            }
            return false;
        }

    } catch (Exception e) {
        // clean up after error...
        if (debug) {
            System.err.println("error during connect: " + e);
            e.printStackTrace();
        }

        if (this.sock.isConnected()) {
            this.sock.close();

        }

        return false;
    }
}

From source file:com.trellmor.berrytube.BerryTubeIOCallback.java

/**
 * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge,
 *      java.lang.Object[])//  w w  w.jav a 2 s  .c o  m
 */
public void on(String event, IOAcknowledge ack, Object... args) {
    if (event.compareTo("chatMsg") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject jsonMsg = (JSONObject) args[0];

            try {
                berryTube.getHandler()
                        .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg"))));
            } catch (JSONException e) {
                Log.e(TAG, "chatMsg", e);
            }
        } else
            Log.w(TAG, "chatMsg message is not a JSONObject");
    } else if (event.compareTo("setNick") == 0) {
        if (args.length >= 1 && args[0] instanceof String) {
            berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0]));
        } else
            Log.w(TAG, "setNick message is not a String");
    } else if (event.compareTo("loginError") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject error = (JSONObject) args[0];
            berryTube.getHandler()
                    .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed")));
        }
    } else if (event.compareTo("userJoin") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_JOIN));
            } catch (JSONException e) {
                Log.e(TAG, "userJoin", e);
            }
        } else
            Log.w(TAG, "userJoin message is not a JSONObject");
    } else if (event.compareTo("newChatList") == 0) {
        berryTube.getHandler().post(berryTube.new UserResetTask());
        if (args.length >= 1 && args[0] instanceof JSONArray) {
            JSONArray users = (JSONArray) args[0];
            for (int i = 0; i < users.length(); i++) {
                JSONObject user = users.optJSONObject(i);
                if (user != null) {
                    try {
                        berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                                BerryTube.UserJoinPartTask.ACTION_JOIN));
                    } catch (JSONException e) {
                        Log.e(TAG, "newChatList", e);
                    }
                }
            }
        } else
            Log.w(TAG, "newChatList message is not a JSONArray");
    } else if (event.compareTo("userPart") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_PART));
            } catch (JSONException e) {
                Log.e(TAG, "userPart", e);
            }
        } else
            Log.w(TAG, "userPart message is not a JSONObject");
    } else if (event.compareTo("drinkCount") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject drinks = (JSONObject) args[0];
            berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks")));
        }
    } else if (event.compareTo("kicked") == 0) {
        berryTube.getHandler().post(berryTube.new KickedTask());
    } else if (event.compareTo("newPoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            ChatMessage msg;

            // Send chat message for new poll
            try {
                msg = new ChatMessage(poll.getString("creator"), poll.getString("title"),
                        ChatMessage.EMOTE_POLL, 0, 0, false, 1);
                berryTube.getHandler().post(berryTube.new ChatMsgTask(msg));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }

            // Create new poll
            try {
                berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll)));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }
        }
    } else if (event.compareTo("updatePoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            try {
                JSONArray votes = poll.getJSONArray("votes");
                int[] voteArray = new int[votes.length()];
                for (int i = 0; i < votes.length(); i++) {
                    voteArray[i] = votes.optInt(i, -1);
                }
                berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray));
            } catch (JSONException e) {
                Log.e(TAG, "updatePoll", e);
            }
        }
    } else if (event.compareTo("clearPoll") == 0) {
        berryTube.getHandler().post(berryTube.new ClearPollTask());
    } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject videoMsg = (JSONObject) args[0];
            try {
                JSONObject video = videoMsg.getJSONObject("video");
                String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8");
                String id = video.getString("videoid");
                String type = video.getString("videotype");
                berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type));
            } catch (JSONException | UnsupportedEncodingException e) {
                Log.w(TAG, e);
            }
        }
    }
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.MobileClientPlaylistsSchema.java

@Override
public MobileClientPlaylistsSchema fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        mKind = jsonObject.optString("kind", null);
        mPlaylistId = jsonObject.optString("id", null);
        mCreationTimestamp = jsonObject.optString("creationTimestamp");
        mLastModifiedTimestamp = jsonObject.optString("lastModifiedTimestamp", null);
        mRecentTimestamp = jsonObject.optString("recentTimestamp");
        mDeleted = jsonObject.optBoolean("deleted");
        mName = jsonObject.optString("name");
        mType = jsonObject.optString("type");
        mShareToken = jsonObject.optString("shareToken");
        mOwnerName = jsonObject.optString("ownerName");
        mOwnerProfilePhotoUrl = jsonObject.optString("ownerProfilePhotoUrl");
        mAccessControlled = jsonObject.optBoolean("accessControlled");
    }//from  w w w. j av  a 2  s .c om

    //This method returns itself to support chaining.
    return this;
}

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void updateLocateHistory(JSONObject messageIn, boolean blocked, String msgType, String time)
        throws JSONException { // Read current history
    SharedPreferences sp = myContext.getSharedPreferences(LocationService.PREFS_NAME, Context.MODE_PRIVATE);
    String historyJsonStr = sp.getString(LocationService.HISTORY_NAME, "{}");
    JSONObject history = new JSONObject(historyJsonStr);
    if (CHAT.equals(msgType)) { // CHAT history, save hole message
        JSONArray chatMessages = history.optJSONArray("chatMessages");
        if (chatMessages == null)
            chatMessages = new JSONArray();
        //Log.d(TAG, "CHAT history TIME: " + time);
        messageIn.put("time", Long.parseLong(time));
        chatMessages.put(messageIn.toString());
        if (chatMessages.length() > 100)
            chatMessages.remove(0); // store only last 100 chat messages
        history.put("chatMessages", chatMessages);
    } else {// Current LOCATE
        String member = messageIn.optString("memberName", "");
        if (blocked)
            member = "\u2717 " + member;
        JSONObject updateStatus = new JSONObject();
        updateStatus.put("member", member);
        updateStatus.put("team", messageIn.optString("teamId", ""));
        updateStatus.put("date", getDateAndTimeString(System.currentTimeMillis()));
        updateStatus.put("target", messageIn.optString("target", ""));
        history.put("updateStatus", updateStatus);
        // History LOCATE lines...
        JSONArray historyLines = history.optJSONArray("lines");
        if (historyLines == null)
            historyLines = new JSONArray();
        String target;//from  w  w w .  j av  a  2 s .co m
        if (updateStatus.getString("target").equals(""))
            target = updateStatus.optString("team");
        else
            target = updateStatus.optString("target");
        String historyLine = updateStatus.getString("member") + " (" + target + ") "
                + updateStatus.getString("date") + "\n";
        historyLines.put(historyLine);
        if (historyLines.length() > 200)
            historyLines.remove(0); // store only last 200 locate queries
        history.put("lines", historyLines);
    }
    // Save new history
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(LocationService.HISTORY_NAME, history.toString());
    editor.commit();
    //Log.d(TAG, "history:" + history.toString());
}

From source file:org.ESLM.Parser.JSONProtoLessonParser.java

private void parseLesson() throws BadFormedJSONExerciseException {
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject jsonLesson = new JSONObject(tokener);
    String title = jsonLesson.optString("title", "Untitled Lesson");
    JSONArray jsonExercises = jsonLesson.optJSONArray("exercises");
    Instruction[] exercises = parseExercises(jsonExercises);
    parsedLesson = new ProtoLesson(title);
    for (Instruction instruction : exercises)
        parsedLesson.addExercise(instruction);
}

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

private static List<LogEntry> parseLogs(final boolean friends, String rawResponse) {
    final List<LogEntry> logs = new ArrayList<LogEntry>();

    // for non logged in users the log book is not shown
    if (StringUtils.isBlank(rawResponse)) {
        return logs;
    }// w w  w.  j a  va2 s  .co m

    try {
        final JSONObject resp = new JSONObject(rawResponse);
        if (!resp.getString("status").equals("success")) {
            Log.e("GCParser.loadLogsFromDetails: status is " + resp.getString("status"));
            return null;
        }

        final JSONArray data = resp.getJSONArray("data");

        for (int index = 0; index < data.length(); index++) {
            final JSONObject entry = data.getJSONObject(index);

            // FIXME: use the "LogType" field instead of the "LogTypeImage" one.
            final String logIconNameExt = entry.optString("LogTypeImage", ".gif");
            final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4);

            long date = 0;
            try {
                date = GCLogin.parseGcCustomDate(entry.getString("Visited")).getTime();
            } catch (final ParseException e) {
                Log.e("GCParser.loadLogsFromDetails: failed to parse log date.");
            }

            // TODO: we should update our log data structure to be able to record
            // proper coordinates, and make them clickable. In the meantime, it is
            // better to integrate those coordinates into the text rather than not
            // display them at all.
            final String latLon = entry.getString("LatLonString");
            final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>"))
                    + TextUtils.removeControlCharacters(entry.getString("LogText"));
            final LogEntry logDone = new LogEntry(
                    TextUtils.removeControlCharacters(entry.getString("UserName")), date,
                    LogType.getByIconName(logIconName), logText);
            logDone.found = entry.getInt("GeocacheFindCount");
            logDone.friend = friends;

            final JSONArray images = entry.getJSONArray("Images");
            for (int i = 0; i < images.length(); i++) {
                final JSONObject image = images.getJSONObject(i);
                final String url = "http://imgcdn.geocaching.com/cache/log/large/"
                        + image.getString("FileName");
                final String title = TextUtils.removeControlCharacters(image.getString("Name"));
                final Image logImage = new Image(url, title);
                logDone.addLogImage(logImage);
            }

            logs.add(logDone);
        }
    } catch (final JSONException e) {
        // failed to parse logs
        Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e);
    }

    return logs;
}

From source file:com.jelly.music.player.GMusicHelpers.WebClientSongsSchema.java

@Override
public WebClientSongsSchema fromJsonObject(JSONObject jsonObject) {

    if (jsonObject != null) {
        mTotalTracks = jsonObject.optInt("totalTracks");
        mSubjectToCuration = jsonObject.optBoolean("subjectToCuration");
        mName = jsonObject.optString("name", null);
        mTotalDiscs = jsonObject.optInt("totalDiscs");
        mTitleNorm = jsonObject.optString("titleNorm", null);
        mAlbumNorm = jsonObject.optString("albumNorm", null);
        mTrack = jsonObject.optInt("track");
        mAlbumArtUrl = jsonObject.optString("albumArtUrl", null);
        mUrl = jsonObject.optString("url", null);
        mCreationDate = jsonObject.optLong("creationDate");
        mAlbumArtistNorm = jsonObject.optString("albumArtistNorm", null);
        mArtistNorm = jsonObject.optString("artistNorm", null);
        mLastPlayed = jsonObject.optLong("lastPlayed");
        mMatchedId = jsonObject.optString("matchedId", null);
        mType = jsonObject.optInt("type");
        mDisc = jsonObject.optInt("disc");
        mGenre = jsonObject.optString("genre", null);
        mBeatsPerMinute = jsonObject.optInt("beatsPerMinute");
        mAlbum = jsonObject.optString("album", null);
        mId = jsonObject.optString("id", null);
        mComposer = jsonObject.optString("composer", null);
        mTitle = jsonObject.optString("title", null);
        mAlbumArtist = jsonObject.optString("albumArtist", null);
        mYear = jsonObject.optInt("year");
        mArtist = jsonObject.optString("artist", null);
        mDurationMillis = jsonObject.optLong("durationMillis");
        mIsDeleted = jsonObject.optBoolean("deleted");
        mPlayCount = jsonObject.optInt("playCount");
        mRating = jsonObject.optString("rating", null);
        mComment = jsonObject.optString("comment", null);
        mPlaylistEntryId = jsonObject.optString("playlistEntryId");
    }//from   w w w  .  jav  a2  s .  co  m

    //This method returns itself to support chaining.
    return this;
}