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");
}
}
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
}
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.
Try this:
JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With