我在android中解析一个json api,看起来像这样:
[
{
"id":70,
"number_of_devices":12,
},
{
"id":71,
"number_of_devices":5,
}
]
现在我想得到所有设备的总数,并将其显示在textview中,并显示所有id的总数,并在另一个textview中显示。 任何人都可以举例说明如何做到这一点,或任何关于此的教程?
感谢您的帮助
答案 0 :(得分:6)
如果你的字符串(myString)中有你的JSON:
JSONArray mArray = new JSONArray(myString);
int id_count = 0;
int devices_count = 0;
int tmp = 0;
for (int i = 0; i<mArray.length(); i++) {
try {
tmp = mArray.getJSONObject(i).getInt("id");
id_count = id_count + 1;
}
catch (JSONException e) {
// If id doesn't exist, this exception is thrown
}
try {
tmp = mArray.getJSONObject(i).getInt("number_of_devices");
devices_count = devices_count + 1;
}
catch (JSONException e) {
// If number_of_devices doesn't exist, this exception is thrown
}
}
myTextView1.text = String.ValueOf(id_count);
myTextView2.text = String.ValueOf(devices_count);
答案 1 :(得分:4)
在这里你可以尝试将json保存到名为jsonString
的String中JSONArray jsonArray = new JSONArray(jsonString );
int count = jsonArray.length();
用于添加到文本视图。
for(int i = 0; i< jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
TextView tv = new TextView(getApplicationContext());
tv.setText(jsonObject.getString("your_key"));
}