JSONArray遍历

// for循环
for (int i = 0; i < jsonArr.size(); i++) {
   JSONObject jsonObject = jsonArr.getJSONObject(i);
    String name = jsonObject.getString("name");
    Integer age = (Integer) jsonObject.get("age");
    System.out.println("name:"+name+";age:"+age);
}
// stream
String str="[{\"name\":\"tom\"},{\"name\":\"tim\"},{\"name\":\"jim\"},{\"name\":\"sam\"},{\"name\":\"ram\"},{\"name\":\"lam\"}]";
JSONArray jsonArray = JSONArray.parseArray(str);
System.out.println(jsonArray);

Set<String> set=new HashSet<>();
jsonArray.stream().filter(Objects::nonNull).forEach(json->{
    set.add(((JSONObject) json).getString("name"));
});

System.out.println(set);
String json="[{'name':'a','age':'18','value':1},{'name':'b','age':'18','value':2}" +
                ",{'name':'b','age':'18','value':3},{'name':'d','age':'18','value':4}" +
                ",{'name':'b','age':'18','value':4},{'name':'d','age':'18','value':5}]";

JSONArray j1=JSON.parseArray(json);

Long collect1 = j1.stream().filter(t -> ((JSONObject) t).getString("age").equals("18")).count();
Long collect2 = j1.stream().filter(t -> ((JSONObject) t).getString("age").equals("18")).map(t -> ((JSONObject) t).getString("name")).distinct().count();
System.out.println("去重前:"+collect1);
System.out.println("去重后:"+collect2);

你可能感兴趣的:(后端技术,json)