Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

parse and get specific field from HTTP response in java

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.

Upvotes: 1

Views: 6188

Answers (2)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

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

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

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.

Upvotes: 1

Related Questions