Android: How to get JSON objects from this json:

This is a JSON array:

{ "server_response": [{ "Total": "135", "Paid": "105", "Rest": "30" }] } 

So how can I get the names of objects? I want to put them in a separate TextView. Thanks.

+3
source share
4 answers

Put it on everything. I mean external onCreate() and thatโ€™s it.

 private <T> Iterable<T> iterate(final Iterator<T> i){ return new Iterable<T>() { @Override public Iterator<T> iterator() { return i; } }; } 

To get the names of objects:

  try { JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";); JSONArray jsonArray = jsonObject.getJSONArray("server_response"); JSONObject object = jsonArray.getJSONObject(0); for (String key : iterate(object.keys())) { // here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW. Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } 

Hope this helps :)

+1
source

My suggestion:

Go to this site:
Json to pojo

Get your pojo classes and then use them on Android.
All you have to do is use Gson.fromGson (options here).
One of your options is a class created using an online schema.

0
source

You can use jackson ObjectMapper for this.

 public class ServerResponse { @JsonProperty("Total") private String total; @JsonProperty("Paid") private String paid; @JsonProperty("Rest") private String rest; //getters and setters //toString() } //Now convert json into ServerResponse object ObjectMapper mapper = new ObjectMapper(); TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { }; Object object = mapper.readValue(jsonString, serverResponse); if (object instanceof ServerResponse) { return (ServerResponse) object; } 
0
source
 JSONObject jsonObject = new JSONObject("Your JSON"); int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total"); int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid"); int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest"); 
-1
source

All Articles