ObjectMapper可以帮助我们从各种数据类型转换成Json数据类型
自己使用的例子,从List<String>转换为Json
ObjectMapper objectMapper = new ObjectMapper();
// queryInvsetDeviceListDTO.getEnvCondition()
// ['1','2'] --->['1':'水']
try {
String resultJsonStr = objectMapper.writeValueAsString(queryInvsetDeviceListDTO.getEnvCondition());
po.setEnvCondition(resultJsonStr);
} catch (Exception e) {
throw new BusinessException("json转换异常!");
}
其中envCondition为List<String>类型
其他例子:
List<Student> studentList= new ArrayList<>();
studentList.add(new Student("hyl1" ,20 , new Date()));
studentList.add(new Student("hyl2" ,21 , new Date()));
studentList.add(new Student("hyl3" ,22 , new Date()));
studentList.add(new Student("hyl4" ,23 , new Date()));
String jsonStr = mapper.writeValueAsString(studentList);
System.out.println(jsonStr);
List<Student> studentList2 = mapper.readValue(jsonStr, List.class);
System.out.println("字符串转集合:" + studentList2 );
结果:
[ {
"name" : "hyl1",
"age" : 20,
"sendTime" : 1525164212803
}, {
"name" : "hyl2",
"age" : 21,
"sendTime" : 1525164212803
}, {
"name" : "hyl3",
"age" : 22,
"sendTime" : 1525164212803
}, {
"name" : "hyl4",
"age" : 23,
"sendTime" : 1525164212803
} ]
[{name=hyl1, age=20, sendTime=1525164212803}, {name=hyl2, age=21, sendTime=1525164212803}, {name=hyl3, age=22, sendTime=1525164212803}, {name=hyl4, age=23, sendTime=1525164212803}]