如何计算 json 对象项?



我正在Android中解析一个JSON字符串,如下所示:

[
{
"id":70,
"selection":"25"
},
{
"id":71,
"selection":"50"
},
{
"id":72,
"selection":"50"
}
]

现在我想获取所有selection的总数并将其显示在文本视图中。谁能给我一个如何做到这一点的例子,或者任何关于这个的教程?

例如:

选择

25 = 1
选择 50 = 2

感谢您的任何帮助!

我认为您要查找的是这样的:

JsonArray selections = new JsonArray(); // This is your parsed json object
HashMap<Integer, Integer> count = new HashMap<>();
for (JsonElement element : selections) {
JsonObject jsonObject = element.getAsJsonObject();
if(jsonObject.has("selection")) {
int selValue = jsonObject.get("selection").getAsInt();
if(count.containsKey(selValue)) {
count.put(selValue, count.get(selValue) + 1);
} else {
count.put(selValue, 1);
}
}
}

这将循环访问您的 json 数组并获取每个选择元素的值。为了跟踪计数,它会递增count哈希映射内的计数。

然后,您可以从哈希映射中获取特定值的计数:

count.get(25); // returns 1
count.get(50); // returns 2
// etc...

如果你在Java 8中使用Jackson,你可以先将给定的JSON字符串转换为List<Map<String, Object>>,然后将其转换为List<Integer>以供选择。最后,您可以按如下方式计算此列表中的出现次数:

ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> jsonObj = mapper.readValue(jsonStr, new TypeReference<List<Map<String, Object>>>(){});
Map<Integer, Long> counted = jsonObj.stream()
.map(x -> Integer.valueOf(x.get("selection").toString()))
.collect(Collectors.toList())
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted.toString());

控制台输出:

{50=2, 25=1}

ArrayList<String> data = new ArrayList<>();
ArrayList<String> datacount = new ArrayList<>();

jsonStr = "Your JSON"
JSONArray jsonArr= null;
try {
jsonArr = new JSONArray(jsonStr);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//here you can set to TextView
String selection = jsonObj.getString("selection");
//System.out.println("adcac"+selection);
if (data.contains(selection)) {
int index = data.indexOf(selection);
int count = Integer.parseInt(datacount.get(index))+1;
//                    System.out.println("Index==="+index+"---count---"+count);
datacount.set(index,String.valueOf(count));
} else {
datacount.add(String.valueOf(1));
data.add(selection);
}
// Here you can get data and data count...  
//                System.out.println("data---"+datacount.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}

你可以获取 JSON 的数组并迭代和计算选择的总和

JSONArray selections = jsonObj.getJSONArray("selections");
// looping through All Selections
int totalCount = selections.length();

为什么没有人使用 Json Path 在两行中解决这个问题?

最新更新