Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

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

public static CommentList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from  ww w  .ja va 2 s . c o  m*/

    CommentList comments = new CommentList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        comments.previous_cursor = jsonObject.optString("previous_cursor", "0");
        comments.next_cursor = jsonObject.optString("next_cursor", "0");
        comments.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("comments");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            comments.commentList = new ArrayList<Comment>(length);
            for (int ix = 0; ix < length; ix++) {
                comments.commentList.add(Comment.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return comments;
}

From source file:com.sina.weibo.sdk_lib.openapi.models.OffsetGeo.java

public static OffsetGeo parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from  ww w  .  j  ava2 s  .  com*/

    OffsetGeo offsetGeo = new OffsetGeo();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            offsetGeo.Geos = new ArrayList<Coordinate>(length);
            for (int ix = 0; ix < length; ix++) {
                offsetGeo.Geos.add(Coordinate.parse(jsonArray.optJSONObject(ix)));
            }
        }

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

    return offsetGeo;
}

From source file:org.privatenotes.Note.java

public Note(JSONObject json) {

    // These methods return an empty string if the key is not found
    setTitle(XmlUtils.unescape(json.optString("title")));
    setGuid(json.optString("guid"));
    setLastChangeDate(json.optString("last-change-date"));
    lastSyncRevision = json.optInt("last-sync-revision", -1);
    setXmlContent(json.optString("note-content"));
    JSONArray jtags = json.optJSONArray("tags");
    String tag;/* ww w.j a  va 2 s . com*/
    tags = new String();
    if (jtags != null) {
        for (int i = 0; i < jtags.length(); i++) {
            tag = jtags.optString(i);
            tags += tag + ",";
        }
    }

    // encryption/decryption
    if (json.optString("encrypted") != null) {
        //<encrypted>
        setEncrypted(json.optString("encrypted").toLowerCase().trim().equals("true"));
    }
    //<encryptedAlgorithm>
    setEncryptedAlgorithm(json.optString("encryptedAlgorithm"));
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*///from ww  w  .  ja v a2  s.c om
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

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

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:org.catnut.fragment.TransientUsersFragment.java

private Response<List<TransientUser>> parseNetworkResponse(NetworkResponse response) {
    try {// w w w  .  j ava 2 s. c om
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject result = new JSONObject(jsonString);
        // set next_cursor
        mNext_cursor = result.optInt(User.next_cursor);
        mTotal_number = result.optInt(User.total_number);
        JSONArray array = result.optJSONArray(User.MULTIPLE);
        if (array != null) {
            List<TransientUser> users = new ArrayList<TransientUser>(array.length());
            for (int i = 0; i < array.length(); i++) {
                users.add(TransientUser.convert(array.optJSONObject(i)));
            }
            return Response.success(users, HttpHeaderParser.parseCacheHeaders(response));
        } else {
            throw new RuntimeException("no users found!");
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    } catch (Exception ex) {
        return Response.error(new ParseError(ex));
    }
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {//w  w w  . j  ava 2  s  .  co m
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            String headerKey = iter.next().toString();
            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();
                headerValues.put(headers.getString(headerKey));
            }
            connection.setRequestProperty(headerKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}

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

@Override
public WebClientPlaylistsSchema fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        mTitle = jsonObject.optString("title", null);
        mPlaylistId = jsonObject.optString("playlistId", null);
        mRequestTime = jsonObject.optLong("requestTime");
        mContinuationToken = jsonObject.optString("continuationToken", null);
        mDifferentialUpdate = jsonObject.optBoolean("differentialUpdate");
        mContinuation = jsonObject.optBoolean("continuation");

        JSONArray songsArray = jsonObject.optJSONArray("playlist");
        mPlaylist = fromJsonArray(songsArray);
    }/*from ww w .  ja va  2s.c om*/

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

From source file:cn.ttyhuo.activity.InfoOwnerActivity.java

protected void setupViewOfHasLogin(JSONObject jObject) {
    try {//from w  w  w  .j a v a  2  s  .c  o  m

        ArrayList<String> pics = new ArrayList<String>();
        JSONArray jsonArray = jObject.optJSONArray("imageList");
        if (jsonArray != null) {
            for (int s = 0; s < jsonArray.length(); s++)
                pics.add(jsonArray.getString(s));
        }
        while (pics.size() < 3)
            pics.add("plus");
        mPicData = pics;
        mPicAdapter.updateData(pics);

        if (jObject.getBoolean("isTruckVerified")) {
            tv_edit_tips.setText("?????");
        } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) {
            tv_edit_tips.setText(
                    "?????????");
        } else {
            tv_edit_tips.setText("??????");
        }

        if (jObject.has("truckInfo")) {
            JSONObject userJsonObj = jObject.getJSONObject("truckInfo");
            if (!userJsonObj.optString("licensePlate").isEmpty()
                    && userJsonObj.optString("licensePlate") != "null")
                mEditChepai.setText(userJsonObj.getString("licensePlate"));
            Integer truckType = userJsonObj.getInt("truckType");
            if (truckType != null && truckType > 0)
                mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                mEditChexing.setText("");
            if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null")
                mEditZaizhong.setText(userJsonObj.getString("loadLimit"));
            if (!userJsonObj.optString("truckLength").isEmpty()
                    && userJsonObj.optString("truckLength") != "null")
                mEditChechang.setText(userJsonObj.getString("truckLength"));
            if (!userJsonObj.optString("modelNumber").isEmpty()
                    && userJsonObj.optString("modelNumber") != "null")
                mEditXinghao.setText(userJsonObj.getString("modelNumber"));

            if (!userJsonObj.optString("seatingCapacity").isEmpty()
                    && userJsonObj.optString("seatingCapacity") != "null")
                mEditZuowei.setText(userJsonObj.getString("seatingCapacity"));
            if (!userJsonObj.optString("releaseYear").isEmpty()
                    && userJsonObj.optString("releaseYear") != "null")
                mEditDate.setText(userJsonObj.getString("releaseYear") + "");
            if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null")
                mEditKuan.setText(userJsonObj.getString("truckWidth"));
            if (!userJsonObj.optString("truckHeight").isEmpty()
                    && userJsonObj.optString("truckHeight") != "null")
                mEditGao.setText(userJsonObj.getString("truckHeight"));
        }

        if (!jObject.getBoolean("isTruckVerified")) {
            mEditChexing.setOnClickListener(this);
            mEditDate.setOnClickListener(this);
            mEditChepai.setFocusable(true);
            mEditChepai.setEnabled(true);
            mEditZaizhong.setFocusable(true);
            mEditZaizhong.setEnabled(true);
            mEditChechang.setFocusable(true);
            mEditChechang.setEnabled(true);
            mEditZuowei.setFocusable(true);
            mEditZuowei.setEnabled(true);
            mEditKuan.setFocusable(true);
            mEditKuan.setEnabled(true);
            mEditGao.setFocusable(true);
            mEditGao.setEnabled(true);
            mEditXinghao.setFocusable(true);
            mEditXinghao.setEnabled(true);
            canUpdate = true;
        } else {
            mPicGrid.setOnItemLongClickListener(null);

            mEditChepai.setFocusable(false);
            mEditChepai.setEnabled(false);
            mEditZaizhong.setFocusable(false);
            mEditZaizhong.setEnabled(false);
            mEditChechang.setFocusable(false);
            mEditChechang.setEnabled(false);
            mEditZuowei.setFocusable(false);
            mEditZuowei.setEnabled(false);
            mEditKuan.setFocusable(false);
            mEditKuan.setEnabled(false);
            mEditGao.setFocusable(false);
            mEditGao.setEnabled(false);
            mEditXinghao.setFocusable(false);
            mEditXinghao.setEnabled(false);
            canUpdate = false;
        }

        saveParams(true);

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

From source file:fr.openbike.android.io.RemoteStationsUpdateHandler.java

/** {@inheritDoc} */
@Override//from  www. ja va 2 s  .  com
public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException {
    long version = jsonBikes.getLong(VERSION);
    String message = jsonBikes.optString(MESSAGE);
    JSONArray stations = jsonBikes.optJSONArray(STATIONS);
    if (stations != null) {
        dbAdapter.cleanAndInsertStations(version, stations);
    }
    return "".equals(message) ? null : message;
}

From source file:org.catnut.fragment.HomeTimelineFragment.java

@Override
protected void refresh() {
    // ???//from w  w w .  j  a va 2  s.c om
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = TweetAPI.homeTimeline(since_id, 0, size, 0, 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.TimelineProcessor(Status.HOME, true),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Status.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, HomeTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}