I've got an Android app in which I get some JSON from an API, which I now need to decode. I'm pretty far, but I'm failing at getting the contents. The JSON I'm receiving looks like this:
{ "messages": [
{
"created": "1391783287",
"id": 1,
"is_supporter": false,
"text": "Behold! This is a message?"
},
{
"created": "1391783287",
"id": 3,
"is_supporter": true,
"text": "Behave! This is an answer!"
}
]}
And I've got this code:
@Override
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
And on the last line of the code above I get an error saying Error: org.json.JSONException: Value {"messages":[{"id":1,"created":"1391788514","text":"How do I pay to an IBAN?","is_supporter":false},{"id":3,"created":"1391788514","text":"What is a payment pool?","is_supporter":false}]} of type org.json.JSONObject cannot be converted to JSONArray
Does anybody have any idea whats wrong here or how I can solve this?
Your String is a JSON object containing a JSON array, try this :
JSONObject myJSON = new JSONObject(result);
JSONArray jArray = myJSON.getJSONArray("messages");
then iterate through your JSONArray ...
int size = jArray.length();
for (int i=0 ; i<size ; i++){
JSONObject itemInArray = jArray.get(i);
// get values inside the object, for example :
String text = itemInArray.getString("text");
}
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