1.首先在pom.xml文件中,加入依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
2.注入
@Autowired
private static final ObjectMapper MAPPER = new ObjectMapper();
3.ObjectMapper的使用
3.1 序列化:将对象转换为json字符串
@Test
public void ObjectMapperTest01() throws JsonProcessingException {
List<Item> list = new ArrayList<>();
list.add(new Item(2L, "坚果手机R1", " 手机", "锤子", 3699.00, "http://image.leyou.com/123.jpg"));
list.add(new Item(3L, "华为META10", " 手机", "华为", 4499.00, "http://image.leyou.com/3.jpg"));
//将Item类转换为json字符串
String s = MAPPER.writeValueAsString(list);
}
3.2 反序列化:将json字符串转换为java对象
(1)反序列化普通对象
String s = “{“name”: “张三”,"age": 10,"sex": "男"}”;
Student student= MAPPER.readValue(s, Student.class);
(2)反序列化为Map集合对象
String s = “{“name”: “张三”,"age": 10,"sex": "男"}”;
Map<String, Object> student = MAPPER.readValue(s, new TypeReference<Map<String, Object>>(){});