Android:如何从此JSON中获取JSON对象键:

3

这是JSON数组:

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

那么,我该如何获取对象名称?我想把它们放在不同的TextView中。 谢谢。

哪些名称是指“Total”和所有的名称? - Janki Gadhiya
请查看此链接:http://www.tutorialspoint.com/android/android_json_parser.htm - namlik
@jankigadhiya 我需要全部。 - László Csiki
4个回答

4
将此放在所有内容之外。我的意思是在onCreate()及其外部。
private <T> Iterable<T> iterate(final Iterator<T> i){
    return new Iterable<T>() {
        @Override
        public Iterator<T> 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();
    }

希望这能帮到你 :)

谢谢!这正是我想要的 :) - László Csiki
还有一件事,我如何在不同的文本视图中设置键? - László Csiki
给我TextView的名称。 - Janki Gadhiya

0
我的建议是:

前往这个网站:
Json to pojo

获取你的pojo类,然后在Android中使用它们。
你所需要做的就是使用Gson.fromGson(params here)。 其中一个参数是你使用在线模式创建的类。


0
你可以使用 jacksonObjectMapper 来实现这个功能。
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;
 }

-1
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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接