1. Stream流 按照两个字段(班级,年龄)分组
//Stream流 按照两个字段(班级,年龄)分组
JSONArray studentList = new JsonArray();
JSONObject student= new JSONObject();
student.put("class","one");
student.put("name","路西法98");
student.put("age","12");
student.put("score",78);
student.put("subject","语文");
JSONObject student2= new JSONObject();
student2.put("class","two");
student2.put("name","德古拉");
student2.put("age","11");
student2.put("score",59);
student2.put("subject","数学");
studentList.add(student);
studentList.add(student2);
Map<String,Map<String, List<Object>>> collect = studentList .stream().collect(
Collectors.groupingBy(item -> ((JSONObject)item).getString("class"), Collectors.groupingBy(item -> ((JSONObject)item).getString("age"))));
2.JsonArray转成Json字符串,属性值为null的属性不显示
//用这种方法把JsonArray转成字符串,属性值为null的属性不会显示
jsonArray.toString();
jsonArray.toJsonString();
//正确做法(这样就可以显示属性值为null的属性)
JSON.toJSONString(jsonArray, SerializerFeature.WriteMapNullValue )
3.JSON和Map、JSONArray和ArrayList 区别
- JSON 和 Map
{"name":"luxifa", "age":24, "job":"JAVAProgrammer"}
{name = luxifa, age = 24, job = JAVAProgrammer}
- JSONArray和ArrayList
[{"name":"luxifa", "age":23}, {"name":"degula", "age":25}]
[{name = luxifa, age = 23}, {name = degula, age = 25}]