1

I try to parse a HTTP response to a JSONObject and retrieve some fields, coould be a String or int. My response is a json array like this:

[{nid: "24161",changed: 1445936169,created: "1444728767",language: "en",status: 1,title: "bicycle",type: "product",uid: "2172",vid: "24161"}]

And I tried using:

JSONObject myObject = new JSONObject(response);

And gson , still after parsing the response turns to {}. Thanks for any help.

2 Answers 2

2

You must use JSONArray instead of JSONObject

JSONArray array = new JSONArray(response);

You can then iterate throw the array and get the fields you want

for(int i=0; i<array.length(); i++) {
    JSONObject object = array.getJSONObject(i);
    String nid = object.getString("nid");
    int changed = object.getInt("changed");
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are parsing json array into object. Use JSONArray instead of JSONObject

JSONArray myArray = new JSONArray(response);

you can get your object by index from your array.

3 Comments

Works like charm, but how to get a field by key?
once you got the object form your array, you can call myObjectAtIndexZero.get("nid")
will it work for other indexes as well, marking your answer as right when I can.

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.