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.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/users/#get_users_search
 *//*from w  ww .  j ava 2s.  c o m*/
public static ArrayList<User> getUserSearch(String q, Integer count, String accessToken)
        throws IOException, JSONException {
    Params params = new Params("/users/search");
    params.put("q", q);
    params.put("count", count);
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray userJSONArray = rootJSON.optJSONArray("data");
    ArrayList<User> users = new ArrayList<>();
    for (int i = 0; i < userJSONArray.length(); i++) {
        JSONObject userJSON = (JSONObject) userJSONArray.get(i);
        users.add(User.fromJSON(userJSON));
    }
    return users;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/relationships/#get_users_follows
 *///ww w  .j a v  a  2  s  .  c  o m
public static ArrayList<User> getUserFollows(String userId, String accessToken)
        throws IOException, JSONException {
    Params params = new Params("/users/" + userId + "/follows");
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray userJSONArray = rootJSON.optJSONArray("data");
    ArrayList<User> users = new ArrayList<>();
    for (int i = 0; i < userJSONArray.length(); i++) {
        JSONObject userJSON = (JSONObject) userJSONArray.get(i);
        users.add(User.fromJSON(userJSON));
    }
    return users;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/relationships/#get_users_followed_by
 *///from ww  w . ja  va  2 s  .  c  o  m
public static ArrayList<User> getUserFollowedBy(String userId, String accessToken)
        throws IOException, JSONException {
    Params params = new Params("/users/" + userId + "/followed-by");
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray userJSONArray = rootJSON.optJSONArray("data");
    ArrayList<User> users = new ArrayList<>();
    for (int i = 0; i < userJSONArray.length(); i++) {
        JSONObject userJSON = (JSONObject) userJSONArray.get(i);
        users.add(User.fromJSON(userJSON));
    }
    return users;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/relationships/#get_incoming_requests
 *//*w ww  .j  a v  a2 s . com*/
public static ArrayList<User> getSelfRequestedBy(String accessToken) throws IOException, JSONException {
    Params params = new Params("/users/self/requested-by");
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray userJSONArray = rootJSON.optJSONArray("data");
    ArrayList<User> users = new ArrayList<>();
    for (int i = 0; i < userJSONArray.length(); i++) {
        JSONObject userJSON = (JSONObject) userJSONArray.get(i);
        users.add(User.fromJSON(userJSON));
    }
    return users;
}

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

public VKApiUserFull parse(JSONObject user) {
    super.parse(user);

    // general/*  w  ww . ja v  a  2s . c om*/
    last_seen = parseLong(user.optJSONObject(LAST_SEEN), "time");
    bdate = user.optString(BDATE);

    JSONObject city = user.optJSONObject(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }
    JSONObject country = user.optJSONObject(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    // education
    universities = new VKList<VKApiUniversity>(user.optJSONArray(UNIVERSITIES), VKApiUniversity.class);
    schools = new VKList<VKApiSchool>(user.optJSONArray(SCHOOLS), VKApiSchool.class);

    // status
    activity = user.optString(ACTIVITY);

    JSONObject status_audio = user.optJSONObject("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    // personal views
    JSONObject personal = user.optJSONObject(PERSONAL);
    if (personal != null) {
        smoking = personal.optInt("smoking");
        alcohol = personal.optInt("alcohol");
        political = personal.optInt("political");
        life_main = personal.optInt("life_main");
        people_main = personal.optInt("people_main");
        inspired_by = personal.optString("inspired_by");
        religion = personal.optString("religion");
        if (personal.has("langs")) {
            JSONArray langs = personal.optJSONArray("langs");
            if (langs != null) {
                this.langs = new String[langs.length()];
                for (int i = 0; i < langs.length(); i++) {
                    this.langs[i] = langs.optString(i);
                }
            }
        }
    }

    // contacts
    facebook = user.optString("facebook");
    facebook_name = user.optString("facebook_name");
    livejournal = user.optString("livejournal");
    site = user.optString(SITE);
    screen_name = user.optString("screen_name", "id" + id);
    skype = user.optString("skype");
    mobile_phone = user.optString("mobile_phone");
    home_phone = user.optString("home_phone");
    twitter = user.optString("twitter");
    instagram = user.optString("instagram");

    // personal info
    about = user.optString(ABOUT);
    activities = user.optString(ACTIVITIES);
    books = user.optString(BOOKS);
    games = user.optString(GAMES);
    interests = user.optString(INTERESTS);
    movies = user.optString(MOVIES);
    quotes = user.optString(QUOTES);
    tv = user.optString(TV);

    // settings
    nickname = user.optString("nickname", null);
    can_post = parseBoolean(user, CAN_POST);
    can_see_all_posts = parseBoolean(user, CAN_SEE_ALL_POSTS);
    blacklisted_by_me = parseBoolean(user, BLACKLISTED_BY_ME);
    can_write_private_message = parseBoolean(user, CAN_WRITE_PRIVATE_MESSAGE);
    wall_comments = parseBoolean(user, WALL_DEFAULT);
    String deactivated = user.optString("deactivated");
    is_deleted = "deleted".equals(deactivated);
    is_banned = "banned".equals(deactivated);
    wall_default_owner = "owner".equals(user.optString(WALL_DEFAULT));
    verified = parseBoolean(user, VERIFIED);

    // other
    sex = user.optInt(SEX);
    JSONObject counters = user.optJSONObject(COUNTERS);
    if (counters != null)
        this.counters = new Counters(counters);

    relation = user.optInt(RELATION);

    if (user.has(RELATIVES)) {
        if (relatives == null) {
            relatives = new VKList<Relative>();
        }
        relatives.fill(user.optJSONArray(RELATIVES), Relative.class);
    }
    return this;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;//from  w  w w  .j av  a 2s  .  c o  m

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

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

protected void refresh() {
    // ???/* w w  w . j  a  v  a  2s . co  m*/
    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 = CommentsAPI.show(mId, since_id, 0, size, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.CommentTweetsProcessor(mId),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(Status.total_number);
                                    // ???
                                    mLastTotalCount = 0;
                                    mShowToastTimes = 0;
                                    JSONArray jsonArray = response.optJSONArray(Status.COMMENTS);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, TweetFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

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

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = CommentsAPI.show(mId, 0, max_id, getFetchSize(), 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.CommentTweetsProcessor(mId),
            new Response.Listener<JSONObject>() {
                @Override//from www .  jav  a 2  s .  c o  m
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(Status.total_number);
                    mLastTotalCount = mAdapter.getCount();
                    int newSize = response.optJSONArray(Status.COMMENTS).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, TweetFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

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

private void loadTweet() {
    // load tweet from local...
    String query = CatnutUtils.buildQuery(
            new String[] { Status.uid, Status.columnText, Status.bmiddle_pic, Status.original_pic,
                    Status.comments_count, Status.reposts_count, Status.attitudes_count, Status.source,
                    Status.favorited, Status.retweeted_status, Status.pic_urls, "s." + Status.created_at,
                    User.screen_name, User.avatar_large, User.remark, User.verified },
            "s._id=" + mId, Status.TABLE + " as s", "inner join " + User.TABLE + " as u on s.uid=u._id", null,
            null);//w ww.ja v a 2s . com
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                Picasso.with(getActivity()).load(cursor.getString(cursor.getColumnIndex(User.avatar_large)))
                        .placeholder(R.drawable.error).error(R.drawable.error).into(mAvatar);
                final long uid = cursor.getLong(cursor.getColumnIndex(Status.uid));
                final String screenName = cursor.getString(cursor.getColumnIndex(User.screen_name));
                mAvatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ProfileActivity.class);
                        intent.putExtra(Constants.ID, uid);
                        intent.putExtra(User.screen_name, screenName);
                        startActivity(intent);
                    }
                });
                String remark = cursor.getString(cursor.getColumnIndex(User.remark));
                mRemark.setText(TextUtils.isEmpty(remark) ? screenName : remark);
                mScreenName.setText(getString(R.string.mention_text, screenName));
                mPlainText = cursor.getString(cursor.getColumnIndex(Status.columnText));
                mText.setText(mPlainText);
                CatnutUtils.vividTweet(mText, mImageSpan);
                CatnutUtils.setTypeface(mText, mTypeface);
                mText.setLineSpacing(0, mLineSpacing);
                int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count));
                mReplayCount.setText(CatnutUtils.approximate(replyCount));
                int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count));
                mReteetCount.setText(CatnutUtils.approximate(retweetCount));
                int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count));
                mFavoriteCount.setText(CatnutUtils.approximate(favoriteCount));
                String source = cursor.getString(cursor.getColumnIndex(Status.source));
                mSource.setText(Html.fromHtml(source).toString());
                mCreateAt.setText(DateUtils.getRelativeTimeSpanString(
                        DateTime.getTimeMills(cursor.getString(cursor.getColumnIndex(Status.created_at)))));
                if (CatnutUtils.getBoolean(cursor, User.verified)) {
                    mTweetLayout.findViewById(R.id.verified).setVisibility(View.VISIBLE);
                }
                String thumb = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic));
                String url = cursor.getString(cursor.getColumnIndex(Status.original_pic));
                loadThumbs(thumb, url, mThumbs,
                        CatnutUtils.optPics(cursor.getString(cursor.getColumnIndex(Status.pic_urls))),
                        mPicsOverflow);
                // retweet
                final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status));
                if (!TextUtils.isEmpty(jsonString)) {
                    View retweet = mRetweetLayout.inflate();
                    try {
                        JSONObject json = new JSONObject(jsonString);
                        JSONObject user = json.optJSONObject(User.SINGLE);
                        String _remark = user.optString(User.remark);
                        if (TextUtils.isEmpty(_remark)) {
                            _remark = user.optString(User.screen_name);
                        }
                        CatnutUtils.setText(retweet, R.id.retweet_nick,
                                getString(R.string.mention_text, _remark));
                        long mills = DateTime.getTimeMills(json.optString(Status.created_at));
                        CatnutUtils.setText(retweet, R.id.retweet_create_at,
                                DateUtils.getRelativeTimeSpanString(mills));
                        TweetTextView retweetText = (TweetTextView) CatnutUtils.setText(retweet,
                                R.id.retweet_text, json.optString(Status.text));
                        CatnutUtils.vividTweet(retweetText, mImageSpan);
                        CatnutUtils.setTypeface(retweetText, mTypeface);
                        retweetText.setLineSpacing(0, mLineSpacing);
                        retweet.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), TweetActivity.class);
                                intent.putExtra(Constants.JSON, jsonString);
                                startActivity(intent);
                            }
                        });
                        retweet.findViewById(R.id.verified)
                                .setVisibility(user.optBoolean(User.verified) ? View.VISIBLE : View.GONE);
                        if (json.has(Status.thumbnail_pic)) {
                            loadThumbs(json.optString(Status.bmiddle_pic), json.optString(Status.bmiddle_pic),
                                    (ImageView) retweet.findViewById(R.id.thumbs),
                                    json.optJSONArray(Status.pic_urls),
                                    retweet.findViewById(R.id.pics_overflow));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "convert text to string error!", e);
                        retweet.setVisibility(View.GONE);
                    }
                }
                // shareAndFavorite&favorite
                shareAndFavorite(CatnutUtils.getBoolean(cursor, Status.favorited), mPlainText);
            }
            cursor.close();
        }
    }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, query, null, null);
}

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

public NovaEmitterVO(final JSONObject json) throws JSONException {
    super(json);//from   w w  w.  ja  v a2 s.c  om

    name = json.optString("name");

    if (json.has("type")) {
        type = json.getString("type");
    }

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

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

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

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

    // offset position
    x = json.optInt("x");
    y = json.optInt("y");

    animator = json.optString("animator");
    motion_trail = json.optString("motion_trail");
    particles = getParticles(json.optJSONArray("particles"));
}