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) 

Source Link

Document

Get an optional string associated with a key.

Usage

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

/**
 * Fills a Post instance from JSONObject.
 *//*from   w  ww  .  j a v  a  2  s .c om*/
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:com.zotoh.maedr.device.netty.WebSockIO.java

@Override
protected void inizWithProperties(JSONObject deviceProperties) throws Exception {
    super.inizWithProperties(deviceProperties);

    String cpath = trim(deviceProperties.optString("uri"));
    tstEStrArg("uri-path", cpath);
    _pathUri = cpath;//  ww  w  .  j  a va2  s .c o  m
}

From source file:com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement.java

@Override
public void showLoanTemplate(ResponseBody result) {

    final ArrayList<PaymentTypeOptions> paymentOption = new ArrayList<PaymentTypeOptions>();
    final ArrayList<String> paymentNames = new ArrayList<String>();
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    String line;//from  w  w w .  ja v a  2 s . c om
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("paymentTypeOptions")) {
            JSONArray paymentOptions = obj.getJSONArray("paymentTypeOptions");
            for (int i = 0; i < paymentOptions.length(); i++) {
                JSONObject paymentObject = paymentOptions.getJSONObject(i);
                PaymentTypeOptions payment = new PaymentTypeOptions();
                payment.setId(paymentObject.optInt("id"));
                payment.setName(paymentObject.optString("name"));
                paymentOption.add(payment);
                paymentNames.add(paymentObject.optString("name"));
                paymentNameIdHashMap.put(payment.getName(), payment.getId());
            }
        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    ArrayAdapter<String> paymentAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, paymentNames);
    paymentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_payment_type.setAdapter(paymentAdapter);
    sp_payment_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            paymentTypeId = paymentNameIdHashMap.get(paymentNames.get(i));
            Log.d("paymentId " + paymentNames.get(i), String.valueOf(paymentTypeId));
            if (paymentTypeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_payment), Toast.LENGTH_SHORT)
                        .show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

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

/**
 * Handle server event messages./*  ww  w.  j  ava 2  s. 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();
    }
}

From source file:com.facebook.internal.FacebookRequestErrorClassification.java

public static FacebookRequestErrorClassification createFromJSON(JSONArray jsonArray) {
    if (jsonArray == null) {
        return null;
    }/*from www.  ja v a  2  s . c  om*/
    Map<Integer, Set<Integer>> otherErrors = null;
    Map<Integer, Set<Integer>> transientErrors = null;
    Map<Integer, Set<Integer>> loginRecoverableErrors = null;
    String otherRecoveryMessage = null;
    String transientRecoveryMessage = null;
    String loginRecoverableRecoveryMessage = null;

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject definition = jsonArray.optJSONObject(i);
        if (definition == null) {
            continue;
        }
        String name = definition.optString(KEY_NAME);
        if (name == null) {
            continue;
        }
        if (name.equalsIgnoreCase(KEY_OTHER)) {
            otherRecoveryMessage = definition.optString(KEY_RECOVERY_MESSAGE, null);
            otherErrors = parseJSONDefinition(definition);
        } else if (name.equalsIgnoreCase(KEY_TRANSIENT)) {
            transientRecoveryMessage = definition.optString(KEY_RECOVERY_MESSAGE, null);
            transientErrors = parseJSONDefinition(definition);
        } else if (name.equalsIgnoreCase(KEY_LOGIN_RECOVERABLE)) {
            loginRecoverableRecoveryMessage = definition.optString(KEY_RECOVERY_MESSAGE, null);
            loginRecoverableErrors = parseJSONDefinition(definition);
        }
    }
    return new FacebookRequestErrorClassification(otherErrors, transientErrors, loginRecoverableErrors,
            otherRecoveryMessage, transientRecoveryMessage, loginRecoverableRecoveryMessage);
}

From source file:com.example.m.niceproject.data.Condition.java

@Override
public void populate(JSONObject data) {
    code = data.optInt("code");
    temperature = data.optInt("temp");
    description = data.optString("text");
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);//from  w w  w.j  a  v  a 2 s .  c  o  m

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

From source file:com.funzio.pure2D.particles.nova.vo.NovaParticleVO.java

public NovaParticleVO(final JSONObject json) throws JSONException {
    super(json);//from ww  w . j a  v a 2  s .  co  m

    name = json.optString("name");

    if (json.has("start_delay")) {
        start_delay = json.getInt("start_delay");
    }

    if (json.has("step_delay")) {
        step_delay = json.getInt("step_delay");
    }

    if (json.has("duration")) {
        duration = json.getInt("duration");
    }

    if (json.has("step_quantity")) {
        step_quantity = json.getInt("step_quantity");
    }

    if (json.has("layer")) {
        layer = json.getInt("layer");
    }

    if (json.has("origin_x")) {
        origin_x = json.getInt("origin_x");
    }

    if (json.has("origin_y")) {
        origin_y = json.getInt("origin_y");
    }

    // optional sprite or clip
    sprite = NovaVO.getListString(json, "sprite");
    start_frame = NovaVO.getListInt(json, "start_frame");
    loop_mode = NovaVO.getListString(json, "loop_mode");

    // basic DisplayObject's properties
    x = NovaVO.getListInt(json, "x");
    y = NovaVO.getListInt(json, "y");
    z = NovaVO.getListFloat(json, "z");
    animator = NovaVO.getListString(json, "animator");
    blend_mode = NovaVO.getListString(json, "blend_mode");
    alpha = NovaVO.getListFloat(json, "alpha");
    color = NovaVO.getListColor(json, "color");
    rotation = NovaVO.getListFloat(json, "rotation");
    scale_x = NovaVO.getListFloat(json, "scale_x");
    scale_y = NovaVO.getListFloat(json, "scale_y");
    skew_x = NovaVO.getListFloat(json, "skew_x");
    skew_y = NovaVO.getListFloat(json, "skew_y");
    motion_trail = NovaVO.getListString(json, "motion_trail");
}

From source file:com.basetechnology.s0.agentserver.field.FloatField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("float"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new FloatField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);/*from  ww w .j a  v  a 2s.  c  om*/
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Extract zip data./*from  w  w  w.ja va  2 s  . c o  m*/
 * 
 * @param zipData An input stream that represents a zipped file.
 * @return True if finished.
 */
public boolean syncAdd(File zipData) {
    boolean finished = false;
    ZipFile z = null;
    ArrayList<Object[]> media = new ArrayList<Object[]>();
    long sizecnt = 0;
    JSONObject meta = null;
    int nextUsn = 0;
    try {
        z = new ZipFile(zipData, ZipFile.OPEN_READ);
        // get meta info first
        ZipEntry metaEntry = z.getEntry("_meta");
        // if (metaEntry.getSize() >= 100000) {
        // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")");
        // return false;
        // }
        meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry)));
        ZipEntry usnEntry = z.getEntry("_usn");
        String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry));
        nextUsn = Integer.parseInt(usnstr);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (ZipException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Then loop through all files
    for (ZipEntry zentry : Collections.list(z.entries())) {
        // Check for zip bombs
        sizecnt += zentry.getSize();
        if (sizecnt > 100 * 1024 * 1024) {
            Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping");
            return false;
        }
        if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) {
            // Ignore previously retrieved meta
            continue;
        } else if (zentry.getName().compareTo("_finished") == 0) {
            finished = true;
        } else {
            String name = meta.optString(zentry.getName());
            if (illegal(name)) {
                continue;
            }
            String path = getDir().concat(File.separator).concat(name);
            try {
                Utils.writeToFile(z.getInputStream(zentry), path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String csum = Utils.fileChecksum(path);
            // append db
            media.add(new Object[] { name, csum, _mtime(name) });
            mMediaDb.execute("delete from log where fname = ?", new String[] { name });
        }
    }

    // update media db and note new starting usn
    if (!media.isEmpty()) {
        mMediaDb.executeMany("insert or replace into media values (?,?,?)", media);
    }
    setUsn(nextUsn); // commits
    // if we have finished adding, we need to record the new folder mtime
    // so that we don't trigger a needless scan
    if (finished) {
        syncMod();
    }
    return finished;
}