Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse simple JSON Array without key

I need help with parsing simple JSONArray like this:

{
 "text":[
  "Morate popuniti polje tekst."
 ]
} 

I have tried with this but I failed:

 if (response_str != null) {
    try {
        JSONObject jsonObj = new JSONObject(response_str);
        JSONArray arrayJson = jsonObj.getJSONArray("text");

        for (int i = 0; i < arrayJson.length(); i++) {
            JSONObject obj = arrayJson.optJSONObject(i);
            error = obj.getString("text");
        }
    }
like image 212
Zookey Avatar asked Apr 30 '14 16:04

Zookey


3 Answers

Your JSONArray is an array of Strings. You can iterate this way

JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");

for (int i = 0; i < arrayJson.length(); i++) {
    String error = arrayJson.getString(i);
    // Do something with each error here
}
like image 62
Dan Harms Avatar answered Sep 29 '22 00:09

Dan Harms


You have a JSONArray text. There is no array of JSONObject.

{  // Json object node 
"text":[ // json array text 
 "Morate popuniti polje tekst." // value
]
} 

Just use

for (int i = 0; i < arrayJson.length(); i++) {
  String value =  arrayJson.get(i);
}

In fact there is no need for a loop as you have only 1 element in json array

You can just use

String value = (String) arrayJson.get(0); // index 0 . need to cast it to string

Or

String value = arrayJson.getString(0); // index 0

http://developer.android.com/reference/org/json/JSONArray.html

public Object get (int index)

Added in API level 1
Returns the value at index.

Throws
JSONException   if this array has no value at index, or if that value is the null reference. This method returns normally if the value is JSONObject#NULL.
public boolean getBoolean (int index)

getString

public String getString (int index)

Added in API level 1
Returns the value at index if it exists, coercing it if necessary.

Throws
JSONException   if no such value exists.
like image 39
Raghunandan Avatar answered Sep 28 '22 23:09

Raghunandan


Try this:

JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);
like image 39
matiash Avatar answered Sep 29 '22 01:09

matiash