将JSON数组数据分组并计数是否具有两个相同的值 [英] Group JSON array data and count it if have two same value

查看:145
本文介绍了将JSON数组数据分组并计数是否具有两个相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的Json需要按 kecamatan 分组,以获取 desa 的数组以及kecamatan是否具有相同数组值的计数。

Following Json needs to group by kecamatan to get array of desa along with count if kecamatan have same array value.

{
"data": [
        {
            "ID": 47,
            "kecamatan": "Benteng",
            "desa": "Benteng Selatan"
        },
        {
            "ID": 48,
            "kecamatan": "Benteng",
            "desa": "Benteng Selatan"
        },
        {
           "ID": 49,
            "kecamatan": "Benteng",
            "desa": "Benteng Utara"
        },
        {
            "ID": 50,
            "kecamatan": "Bontomantene",
            "desa": "Garaupa"
        }
    ]
}

预期输出:-


  • Benteng [Benteng selatan] = 2

  • Benteng [Benteng Utara] = 1
  • Bontomantene [Garaupa] = 1

推荐答案

请尝试

private void jsonObject() {
    String result =  "{\"data\": [{\"ID\": 47,\"kecamatan\": \"Benteng\",\"desa\": \"Benteng Selatan\"},{\"ID\": 48,\"kecamatan\": \"Benteng\",\"desa\": \"Benteng Selatan\"},{\"ID\": 49,\"kecamatan\": \"Benteng\",\"desa\": \"Benteng Utara\" },{\"ID\": 50,\"kecamatan\": \"Bontomantene\",\"desa\": \"Garaupa\"}]}";
    try {
        JSONObject jsonObject = new JSONObject(result);
        HashMap<String,Integer> hashMap = new HashMap<>();
        for (int i=0;i<jsonObject.getJSONArray("data").length();i++){
            JSONObject innerJsonObject = jsonObject.getJSONArray("data").getJSONObject(i);
            String key = innerJsonObject.getString("kecamatan")+" ["+innerJsonObject.getString("desa")+"]";
            if(hashMap.containsKey(key)){
                int count = hashMap.get(key)+1;
                hashMap.put(key,count);
            }else {
                hashMap.put(key,1);
            }
        }
        Log.e("Hashmap---",hashMap.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

这篇关于将JSON数组数据分组并计数是否具有两个相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆