Android/Java Json对象计数

 雨霖铃111130 发布于 2023-02-13 13:08

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

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

现在我想得到所有设备的总数,并将其显示在textview中,并显示所有id的总数,并在另一个textview中显示.任何人都可以给我一个例子,如何做到这一点,或任何有关这方面的教程?

谢谢你的帮助

1 个回答
  • 如果你在字符串(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);
    

    2023-02-13 13:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有