Android / Java Json 对象计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20336453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:09:30  来源:igfitidea点击:

Android / Java Json Objects count

javaandroidjson

提问by Deniz Celebi

I'm parsing in android a json api which looks like this:

我在 android 中解析一个 json api,它看起来像这样:

 [
   {
     "id":70,
     "number_of_devices":12,
    },
    {
      "id":71,
      "number_of_devices":5,
    }
   ]

Now I want to get the total count of all devices and display it inside a textview and the total count of all id's and display this inside another textview. Can any one give me an example how to do this, or any tutorial about this ?

现在我想获取所有设备的总数并将其显示在一个文本视图中,以及所有 id 的总数并将其显示在另一个文本视图中。任何人都可以给我一个如何做到这一点的例子,或者任何关于这个的教程?

Thanks for any help

谢谢你的帮助

采纳答案by Xithias

If you've got your JSON in a String (myString):

如果您将 JSON 放入字符串 (myString) 中:

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

回答by bobby.dhillon

Here you can try save json into String called jsonString

在这里您可以尝试将 json 保存到名为 jsonString 的 String 中

JSONArray jsonArray = new JSONArray(jsonString );

int count = jsonArray.length();

For adding to text view.

用于添加到文本视图。

for(int i = 0; i< jsonArray.length();i++) {
       JSONObject jsonObject = jsonArray.getJSONObject(i);

       TextView tv = new TextView(getApplicationContext());

       tv.setText(jsonObject.getString("your_key"));
}