当我们用sql查出来一些值,想要把它打包成一个JSON格式,例如我们查出的数据如下
java
班级 姓名 年龄 性别 身高
1班 AAA 11 男 296cm
1班 BBB 11 男 296cm
2班 CCC 11 男 296cm
2班 DDD 11 男 296cm
2班 EEE 11 男 296cm
3班 FFF 11 男 296cm
要将他变成JSON格式
java
{
"school": [{
"班级": "1班",
"student": [{
"姓名": "AAA",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}, {
"姓名": "BBB",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}]
},{
"班级": "2班",
"student": [{
"姓名": "CCC",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}, {
"姓名": "DDD",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}, {
"姓名": "EEE",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}]
},{
"班级": "3班",
"student": [{
"姓名": "FFF",
"年龄": "11",
"性别": "男",
"身高": "296cm"
}]
}]
}
代码如下
java
Map<String, Object> schoolMap = new HashMap<>();
if (manifest.size() != 0){
List<Map<String, Object>> chalssList = new ArrayList<>();
for (int i = 0; i < t.size(); i++) {
Map<String, Object> classMap = new HashMap<>();
List<student>studentList = new ArrayList;
if (*.size() !=0){
// 假设数据已经从数据库中查询出来并存储在List<Map<String, String>>中
List<Map<String, String>> contentList = new ArrayList<>();
for (int j = 0; j < /.size(); j++) {
Map<String, String> data = new HashMap<>();
data.put("姓名", student.get(j).getName);
data.put("年龄", student.get(j).getAge);
data.put("性别", student.get(j).getSex);
data.put("身高", student.get(j).getLength());
contentList.add(data);
}
String class = student.getClass();
classMap.put("班级", class);
classMap.put("content", student);
}
chalssList.add(manifestMap);
}
schoolMap.put("school", school);
}
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
json = objectMapper.writeValueAsString(schoolMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("json格式:"+json);