我在android中解析一个json api,看起来像这样:
[ { "id":70, "number_of_devices":12, }, { "id":71, "number_of_devices":5, } ]
现在我想得到所有设备的总数,并将其显示在textview中,并显示所有id的总数,并在另一个textview中显示.任何人都可以给我一个例子,如何做到这一点,或任何有关这方面的教程?
谢谢你的帮助
如果你在字符串(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);