How to parsing JSON like this?

122 views Asked by At

I have json data format like

{
   "status":200,
   "message":"ok",
   "response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
   }
}

I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse

protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
3

There are 3 answers

2
Francis Nduba Numbi On
    protected void onPostExecute (String result){
    try {
    JSONObject json = new JSONObject(result);
    JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
     tv.setText(jarr.get(0).toString(1));
    }catch (JSONException e){
     e.printStackTrace(); 
    }
     }
0
pvkcse On

You can use jackson library for json parsing.

ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");

You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.

8
joao86 On

You can use GSON

Create a POJO for your response

public class Response{
   private int result;
   private double time;
   private ArrayList<Integer> values;

   // create SET's and GET's
}

And then use GSON to create the object you desire.

protected void onPostExecute (String result){
  try {
     Gson gson = new GsonBuilder().create();
     Response p = gson.fromJson(result, Response.class);
     tv.setText(p.getValues());
  }catch (JSONException e){
    e.printStackTrace();
  }
}