Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to decode JSON within Android? What am I doing wrong?

Tags:

java

json

android

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?

like image 871
kramer65 Avatar asked Jun 17 '26 14:06

kramer65


1 Answers

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");
}
like image 155
2Dee Avatar answered Jun 19 '26 03:06

2Dee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!