Json序列化与反序列化

Json序列化与反序列化

Jackson

常见的json解析器:Jsonlib,Gson,fastjson,jackson。我们这里用jackson

导入jackson的相关jar包

1
2
3
4
5
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>

使用Jackson核心对象 ObjectMapper完成转换

  1. 反序列化:JSON转为Java对象

    • readValue(json字符串数据, Class)
      • 复杂Class可以使用new TypeReference<Class>(){};
  2. 序列化:Java对象转换JSON字符串

    • writeValueAsString(obj)
    • writeValue(File,obj)
    • writeValue(Writer,obj)
    • writeValue(OutputStream,obj)

常用注解

  • @JsonIgnore:排除属性(不序列化该属性)。

  • @JsonFormat:格式化属性值

    1
    2
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

例子

  • pojo
1
2
3
4
5
6
7
8
9
10
11
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Goods {
private Long skuId;
private String title;
private Long price;

@JsonFormat(pattern = "yyyy-MM-dd hh:mm")
private Date createTime;
}
  • test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
ObjectMapper objectMapper = new ObjectMapper();

// 序列/反序列一个普通pojo对象
@Test
public void testObject() throws JsonProcessingException {
Goods goods = new Goods(1L, "一加6", 11110L, new Date());

// 序列化
String goodsJson = objectMapper.writeValueAsString(goods);
System.out.println("goodsJson = " + goodsJson);

// 反序列化
Goods g = objectMapper.readValue(goodsJson, Goods.class);
System.out.println("g = " + g);
}


// 序列/反序列一个集合
@Test
public void testList() throws JsonProcessingException {
ArrayList<Goods> goodsList = new ArrayList<>();
goodsList.add(new Goods(1L, "一加6", 11110L, new Date()));
goodsList.add(new Goods(2L, "一加7", 2222220L, new Date()));

// 序列化
String json = objectMapper.writeValueAsString(goodsList);
System.out.println("json = " + json);

// 反序列化
List list = objectMapper.readValue(json, new TypeReference<List<Goods>>() {
});
System.out.println("list = " + list);
}

// 序列/反序列一个map
@Test
public void testMap() throws JsonProcessingException {
HashMap<Integer, Goods> map = new HashMap<>();
map.put(1, new Goods(1L, "一加6", 11110L, new Date()));
map.put(2, new Goods(2L, "一加7", 2222220L, new Date()));

// 序列化
String json = objectMapper.writeValueAsString(map);
System.out.println("json = " + json);

// 反序列化
Map<Integer, Goods> goodsMap = objectMapper.readValue(json, new TypeReference<Map<Integer, Goods>>() {
});
System.out.println("goodsMap = " + goodsMap);
}

 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×