简体   繁体   中英

How to convert the json array to string array in android?

I am converting an json array to string array thats doesn't exist any tag. I tried with all tricks but not succeeded.

json array:-

"validValues":["01_Abacus","02_AlarmClock","03_Basketball","04_Beaker","55_Watch"]

Code for convert the json array to string values

if (jsonComponentObj.has(TAG_VALID_VALUES)) {
                    String value = jsonComponentObj.getString(TAG_VALID_VALUES);
                    Logs.e("value " + value);
                    if (!value.equals("null")) {
                        JSONArray jsonArray = jsonComponentObj
                                .getJSONArray(TAG_VALID_VALUES);

                        if (jsonArray != null) {
                            ArrayList<String> stringArray = new ArrayList<String>();
                            for (int j = 0; j < jsonArray.length(); j++) {
                                try {
                                    JSONObject jsonObject = jsonArray
                                            .getJSONObject(j);
                                    stringArray.add(jsonObject.toString());
                                } catch (JSONException e) {
                                    Logs.e("Exception: "+e.toString());
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }

Exception:

org.json.JSONException: Value 01_Abacus at 0 of type java.lang.String cannot be converted to JSONObject

If anyone have idea. Please reply. Thanks in advance..

Because validValues JSONArray contain only Strings instead of JSONObject .so get all values from JSONArray as:

for (int j = 0; j < jsonArray.length(); j++) {

           String str_value = jsonArray.optString(j);
           stringArray.add(str_value);

   }

Your json array contains Strings not json object .Therefore to get Strings from json array directly use getString() ,So Change

JSONObject jsonObject = jsonArray.getJSONObject(j);
stringArray.add(jsonObject.toString());

to

 stringArray.add(jsonArray.getString(j));

or

stringArray.add(jsonArray.optString(j));

You should use optString(int) to coerce a string value from array. Using getString(int) would cause problems if ever the values in the array were not strings.

for (int j = 0; j < jsonArray.length(); j++) {
    String value = jsonArray.optString(j);
    stringArray.add(value);     
}

If you want to give a default value, use optString(int, String) .

try JSONObject jsonObject = jsonArray.getString(j);

instead of JSONObject jsonObject = jsonArray.getJSONObject(j);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM