Example usage for org.json JSONArray optString

List of usage examples for org.json JSONArray optString

Introduction

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

Prototype

public String optString(int index) 

Source Link

Document

Get the optional string value associated with an index.

Usage

From source file:com.basho.riak.client.http.util.TestClientUtils.java

@Test
public void json_opt_string_handles_any_type_and_nulls_without_throwing() throws JSONException {
    // optString() is used by jsonObjectAsMap and jsonArrayAsList with the
    // assumption that
    // it won't throw. Just making sure...
    JSONObject jsonObject = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    assertEquals("", jsonObject.optString("k"));
    assertEquals("", jsonArray.optString(0));

    jsonObject.put("k", new JSONArray());
    jsonArray.put(0, new JSONArray());
    assertEquals("[]", jsonObject.optString("k"));
    assertEquals("[]", jsonArray.optString(0));

    jsonObject.put("k", new JSONObject());
    jsonArray.put(0, new JSONObject());
    assertEquals("{}", jsonObject.optString("k"));
    assertEquals("{}", jsonArray.optString(0));

    jsonObject.put("k", 12);
    jsonArray.put(0, 12);//from  w w w  .  j  av  a  2  s.c o m
    assertEquals("12", jsonObject.optString("k"));
    assertEquals("12", jsonArray.optString(0));

    jsonObject.put("k", true);
    jsonArray.put(0, true);
    assertEquals("true", jsonObject.optString("k"));
    assertEquals("true", jsonArray.optString(0));
}

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

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

    // general/*from   w w  w .  j a  v  a  2  s. c o m*/
    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:br.com.brunogrossi.MediaScannerPlugin.MediaScannerPlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {//from   w w w  . java  2  s.co m
        if (action.equals("scanFile")) {
            String fileUri = args.optString(0);
            if (fileUri != null && !fileUri.equals("")) {
                Uri contentUri = Uri.parse(fileUri);

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaScanIntent.setData(contentUri);
                this.cordova.getActivity().sendBroadcast(mediaScanIntent);

                callbackContext.success();

                return true;
            } else {
                Log.w(TAG, "No action param provided: " + action);
                callbackContext.error("No action param provided: " + action);
                return false;
            }
        } else {
            Log.w(TAG, "Wrong action was provided: " + action);
            return false;
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
        return false;
    }
}

From source file:com.google.blockly.model.Input.java

/**
 * Gets a list of connection checks from JSON. If json does not contain a 'check' field
 * null will be returned instead.//from   w  w w  .j  a v a  2s  .  co  m
 *
 * @param json The JSON to extract the connection checks from.
 * @param checksKey The key for the checks.
 *
 * @return The set of checks or null.
 */
@Nullable
public static String[] getChecksFromJson(JSONObject json, String checksKey) {
    Object checkObj = json.opt(checksKey);
    String[] checks = null;
    if (checkObj == null) {
        // Do nothing, ignore other checks
    } else if (checkObj instanceof JSONArray) {
        JSONArray jsonChecks = (JSONArray) checkObj;
        if (jsonChecks != null) {
            int count = jsonChecks.length();
            checks = new String[count];
            for (int i = 0; i < count; i++) {
                checks[i] = jsonChecks.optString(i);
                if (checks[i] == null) {
                    throw new IllegalArgumentException("Malformatted check array in Input.");
                }
            }
        }
    } else if (checkObj instanceof String) {
        checks = new String[] { (String) checkObj };
    }
    return checks;
}

From source file:com.rapid.actions.Database.java

public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application,
        DataFactory df) throws Exception {

    // place holder for the object we're going to return
    JSONObject jsonData = null;/*from w  w w  .ja  v  a 2s .  c  o m*/

    // retrieve the sql
    String sql = _query.getSQL();

    // only if there is some sql is it worth going further
    if (sql != null) {

        // get any json inputs
        JSONObject jsonInputData = jsonAction.optJSONObject("data");

        // initialise the parameters list
        ArrayList<Parameters> parametersList = new ArrayList<Parameters>();

        // populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
        if (_query.getInputs() == null) {

            // just add an empty parameters member if no inputs
            parametersList.add(new Parameters());

        } else {

            // if there is input data
            if (jsonInputData != null) {

                // get any input fields
                JSONArray jsonFields = jsonInputData.optJSONArray("fields");
                // get any input rows
                JSONArray jsonRows = jsonInputData.optJSONArray("rows");

                // if we have fields and rows
                if (jsonFields != null && jsonRows != null) {

                    // loop the input rows (only the top row if not multirow)
                    for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i++) {

                        // get this jsonRow
                        JSONArray jsonRow = jsonRows.getJSONArray(i);
                        // make the parameters for this row
                        Parameters parameters = new Parameters();

                        // loop the query inputs
                        for (Parameter input : _query.getInputs()) {
                            // get the input id
                            String id = input.getItemId();
                            // get the input field
                            String field = input.getField();
                            // add field to id if present
                            if (field != null && !"".equals(field))
                                id += "." + field;
                            // retain the value
                            String value = null;
                            // if it looks like a control, or a system value (bit of extra safety checking)
                            if ("P".equals(id.substring(0, 1)) && id.indexOf("_C") > 0
                                    || id.indexOf("System.") == 0) {
                                // loop the json inputs looking for the value
                                if (jsonInputData != null) {
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // get the id from the fields
                                        String jsonId = jsonFields.optString(j);
                                        // if the id we want matches this one 
                                        if (id.toLowerCase().equals(jsonId.toLowerCase())) {
                                            // get the value
                                            value = jsonRow.optString(j, null);
                                            // no need to keep looking
                                            break;
                                        }
                                    }
                                }
                            }
                            // if still null try the session
                            if (value == null)
                                value = (String) rapidRequest.getSessionAttribute(input.getItemId());
                            // add the parameter
                            parameters.add(value);
                        }

                        // add the parameters to the list
                        parametersList.add(parameters);

                    } // row loop

                } // input fields and rows check

            } // input data check

        } // query inputs check

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Database action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());

        }

        // if there isn't a cache or no data was retrieved
        if (jsonData == null) {

            try {

                // instantiate jsonData
                jsonData = new JSONObject();
                // fields collection
                JSONArray jsonFields = new JSONArray();
                // rows collection can start initialised
                JSONArray jsonRows = new JSONArray();

                // trim the sql
                sql = sql.trim();

                // check the verb
                if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with")) {

                    // set readonly to true (makes for faster querying)
                    df.setReadOnly(true);

                    // loop the parameterList getting a result set for each parameters (input row)
                    for (Parameters parameters : parametersList) {

                        // get the result set!
                        ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                        // get it's meta data for the field names
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // got fields indicator
                        boolean gotFields = false;

                        // loop the result set
                        while (rs.next()) {

                            // initialise the row
                            JSONArray jsonRow = new JSONArray();

                            // loop the columns
                            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                                // add the field name to the fields collection if not done yet
                                if (!gotFields)
                                    jsonFields.put(rsmd.getColumnLabel(i + 1));
                                // get the column type
                                int columnType = rsmd.getColumnType(i + 1);
                                // add the data to the row according to it's type   
                                switch (columnType) {
                                case (Types.NUMERIC):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                case (Types.INTEGER):
                                    jsonRow.put(rs.getInt(i + 1));
                                    break;
                                case (Types.BIGINT):
                                    jsonRow.put(rs.getLong(i + 1));
                                    break;
                                case (Types.FLOAT):
                                    jsonRow.put(rs.getFloat(i + 1));
                                    break;
                                case (Types.DOUBLE):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                default:
                                    jsonRow.put(rs.getString(i + 1));
                                }
                            }
                            // add the row to the rows collection
                            jsonRows.put(jsonRow);
                            // remember we now have our fields
                            gotFields = true;

                        }

                        // close the record set
                        rs.close();

                    }

                } else {

                    // assume rows affected is 0
                    int rows = 0;

                    // sql check
                    if (sql.length() > 0) {

                        // perform update for all incoming parameters (one parameters collection for each row)
                        for (Parameters parameters : parametersList) {
                            rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
                        }

                        // add a psuedo field 
                        jsonFields.put("rows");

                        // create a row array
                        JSONArray jsonRow = new JSONArray();
                        // add the rows updated
                        jsonRow.put(rows);
                        // add the row we just made
                        jsonRows.put(jsonRow);

                    }

                }

                // add the fields to the data object
                jsonData.put("fields", jsonFields);
                // add the rows to the data object
                jsonData.put("rows", jsonRows);

                // check for any child database actions
                if (_childDatabaseActions != null) {
                    // if there really are some
                    if (_childDatabaseActions.size() > 0) {
                        // get any child data
                        JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
                        // if there was some
                        if (jsonChildQueries != null) {
                            // loop
                            for (int i = 0; i < jsonChildQueries.length(); i++) {
                                // fetch the data
                                JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
                                // read the index (the position of the child this related to
                                int index = jsonChildAction.getInt("index");
                                // get the relevant child action
                                Database childDatabaseAction = _childDatabaseActions.get(index);
                                // get the resultant child data
                                JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest,
                                        jsonChildAction, application, df);

                                // a map for indexes of matching fields between our parent and child
                                Map<Integer, Integer> fieldsMap = new HashMap<Integer, Integer>();
                                // the child fields
                                JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
                                if (jsonChildFields != null) {
                                    // loop the parent fields
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // loop the child fields
                                        for (int k = 0; k < jsonChildFields.length(); k++) {
                                            // get parent field
                                            String field = jsonFields.getString(j);
                                            // get child field
                                            String childField = jsonChildFields.getString(k);
                                            // if both not null
                                            if (field != null && childField != null) {
                                                // check for match
                                                if (field.toLowerCase().equals(childField.toLowerCase()))
                                                    fieldsMap.put(j, k);
                                            }
                                        }
                                    }
                                }

                                // add a field for the results of this child action
                                jsonFields.put("childAction" + (i + 1));

                                // if matching fields
                                if (fieldsMap.size() > 0) {
                                    // an object with a null value for when there is no match
                                    Object nullObject = null;
                                    // get the child rows
                                    JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
                                    // if we had some
                                    if (jsonChildRows != null) {
                                        // loop the parent rows
                                        for (int j = 0; j < jsonRows.length(); j++) {
                                            // get the parent row
                                            JSONArray jsonRow = jsonRows.getJSONArray(j);
                                            // make a new rows collection for the child subset
                                            JSONArray jsonChildRowsSubset = new JSONArray();
                                            // loop the child rows
                                            for (int k = 0; k < jsonChildRows.length(); k++) {
                                                // get the child row
                                                JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
                                                // assume no matches
                                                int matches = 0;
                                                // loop the fields map
                                                for (Integer l : fieldsMap.keySet()) {
                                                    // parent value
                                                    Object parentValue = null;
                                                    // get the value if there are enough
                                                    if (jsonRow.length() > l)
                                                        parentValue = jsonRow.get(l);
                                                    // child value
                                                    Object childValue = null;
                                                    if (jsonChildRow.length() > l)
                                                        childValue = jsonChildRow.get(fieldsMap.get(l));
                                                    // non null check
                                                    if (parentValue != null && childValue != null) {
                                                        // a string we will concert the child value to
                                                        String parentString = null;
                                                        // check the parent value type
                                                        if (parentValue.getClass() == String.class) {
                                                            parentString = (String) parentValue;
                                                        } else if (parentValue.getClass() == Integer.class) {
                                                            parentString = Integer
                                                                    .toString((Integer) parentValue);
                                                        } else if (parentValue.getClass() == Long.class) {
                                                            parentString = Long.toString((Long) parentValue);
                                                        } else if (parentValue.getClass() == Double.class) {
                                                            parentString = Double
                                                                    .toString((Double) parentValue);
                                                        } else if (parentValue.getClass() == Boolean.class) {
                                                            parentString = Boolean
                                                                    .toString((Boolean) parentValue);
                                                        }
                                                        // a string we will convert the child value to
                                                        String childString = null;
                                                        // check the parent value type
                                                        if (childValue.getClass() == String.class) {
                                                            childString = (String) childValue;
                                                        } else if (childValue.getClass() == Integer.class) {
                                                            childString = Integer
                                                                    .toString((Integer) childValue);
                                                        } else if (childValue.getClass() == Long.class) {
                                                            childString = Long.toString((Long) childValue);
                                                        } else if (childValue.getClass() == Double.class) {
                                                            childString = Double.toString((Double) childValue);
                                                        } else if (childValue.getClass() == Boolean.class) {
                                                            childString = Boolean
                                                                    .toString((Boolean) childValue);
                                                        }
                                                        // non null check
                                                        if (parentString != null && childString != null) {
                                                            // do the match!
                                                            if (parentString.equals(childString))
                                                                matches++;
                                                        }
                                                    } // values non null                                          
                                                } // field map loop
                                                  // if we got some matches for all the fields add this row to the subset
                                                if (matches == fieldsMap.size())
                                                    jsonChildRowsSubset.put(jsonChildRow);
                                            } // child row loop
                                              // if our child subset has rows in it
                                            if (jsonChildRowsSubset.length() > 0) {
                                                // create a new childSubset object
                                                JSONObject jsonChildDataSubset = new JSONObject();
                                                // add the fields
                                                jsonChildDataSubset.put("fields", jsonChildFields);
                                                // add the subset of rows
                                                jsonChildDataSubset.put("rows", jsonChildRowsSubset);
                                                // add the child database action data subset
                                                jsonRow.put(jsonChildDataSubset);
                                            } else {
                                                // add an empty cell
                                                jsonRow.put(nullObject);
                                            }
                                        } // parent row loop                                 
                                    } // jsonChildRows null check
                                } else {
                                    // loop the parent rows
                                    for (int j = 0; j < jsonRows.length(); j++) {
                                        // get the row
                                        JSONArray jsonRow = jsonRows.getJSONArray(j);
                                        // add the child database action data
                                        jsonRow.put(jsonChildData);
                                    }
                                } // matching fields check

                            } // jsonChildQueries loop
                        } // jsonChildQueries null check                      
                    } // _childDatabaseActions size > 0                                                      
                } // _childDatabaseActions not null

                // cache if in use
                if (actionCache != null)
                    actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);

            } catch (Exception ex) {

                // log the error
                _logger.error(ex);

                // close the data factory and silently fail
                try {
                    df.close();
                } catch (Exception ex2) {
                }

                // only throw if no action cache
                if (actionCache == null) {
                    throw ex;
                } else {
                    _logger.debug("Error not shown to user due to cache : " + ex.getMessage());
                }

            } // jsonData not null

        } // jsonData == null

    } // got sql

    return jsonData;

}

From source file:org.smilec.smile.bu.json.AnswersAndRatingsJSONParser.java

public static final void process(JSONObject object, Map<String, Student> students,
        Map<Integer, Question> questions) {

    String ip = object.optString(IP);

    Student student = students.get(ip);/*from  www. j  ava 2  s  . com*/
    if (student != null) {
        student.setSolved(true);
    }

    JSONArray answersArray = object.optJSONArray(ANSWERS);
    JSONArray ratingsArray = object.optJSONArray(RATINGS);

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

        Question question = questions.get(i + 1);
        if (question == null) {
            continue;
        }

        String sRating = ratingsArray.optString(i);
        String sAnswer = answersArray.optString(i);

        if (sRating != null && sRating.trim().length() > 0) {

            Integer rating = Integer.valueOf(sRating);

            question.addRating(rating);
            student.addRating(question, rating);
        }

        if (sAnswer != null && sAnswer.trim().length() > 0) {

            Integer answer = Integer.valueOf(sAnswer);

            question.addAnswer(answer);
            student.addAnswer(question, answer);

        }

    }

}