5

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");
        }
    }

3 Answers 3

9

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works, but Raghunandan answered first, so I will acpet his answer, sorry. Anyway, thank you, this is more complete and clear solution.
You are free to pick whichever answer you like, but if it is a more complete and clear solution, maybe it should be chosen?
He answered faster than you, so I test it and it works, that's fair.
7

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.

1 Comment

Anyway, dcharms answer is more clear, so you should edit your, because somebody else could have same problem.
3

Try this:

JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.