jackson学习(二):json字符串转自定义类

用途

字符串转自定义类这种方式非常常见,比如在做微信开发、调用第三方接口时,返回的json字符串基本都是这种方式,如果你学到了这一节的方法,你的开发效率会提高很多!

参考项目:https://github.com/bigbeef/cppba-jackson
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

说明:jackson介绍和maven配置在第一节说过了,有不明白的同学可以翻一翻第一节

编写测试代码

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
package com.cppba.jackson;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class StringToObject {
public static void main(String[] args) throws IOException {
String jsonString = "{\"id\":\"1\",\"name\":\"bigbeef\",\"list\":[{\"str\":\"str1\",\"integer\":\"1\"}," +
"{\"str\":\"str2\",\"integer\":\"2\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
System.out.println(myObject.toString());
}
}

class MyObject{
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("list")
private List<MyListProject> list;

@Override
public String toString() {
return "MyObject{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", list=" + list +
'}';
}
}

class MyListProject{
@JsonProperty("str")
private String str;
@JsonProperty("integer")
private Integer integer;
@Override
public String toString() {
return "MyListProject{" +
"str='" + str + '\'' +
", integer=" + integer +
'}';
}
}

运行结果

https://github.com/bigbeef