Android:如何从这个json获取JSON对象键:

这是JSON数组:

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

那么,我怎样才能获得对象名称? 我想把它们放在单独的TextView中。 谢谢。

把这一切都放在一边。 我的意思是外面的onCreate()和所有。

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

获取对象的名称:

  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(); } 

希望这可以帮助 :)

我的建议:

转到这个网站:
Json到pojo

获取您的pojo课程,然后在Android中使用它们。
您需要做的就是使用Gson.fromGson(此处为params)。
您的一个参数是使用在线模式创建的类。

您可以使用jackson ObjectMapper来执行此操作。

 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 = new TypeReference() { }; Object object = mapper.readValue(jsonString, serverResponse); if (object instanceof ServerResponse) { return (ServerResponse) object; } 
 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");