简介
通俗的来说,Jackson 是一个 Java 用来处理 JSON 格式数据的类库 ,其性能非常好
Jackson 具有比较高的序列化 和反序列化 效率,据测试,无论是哪种形式的转换,Jackson > Gson > Json-lib ,而且Jackson的处理能力甚至高出Json-lib近10倍左右 ,且正确性也十分高。相比之下,Json-lib似乎已经停止更新 ,最新的版本也是基于JDK15,而Jackson的社区则较为活跃
Jackson提供了很多类和方法,而在序列化和反序列化中 使用的最多的类则是ObjectMapper 这个类,此类比较类似于Json-lib中JsonObject和ArrayObject 。此类中提供了`readTree(),readValue(),writeValueAsString()等方法用于转换。具体关于此类的说明文档地址是:
com.fasterxml.jackson.databind.ObjectMapper
http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html
使用
引入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.10</version>
</dependency>
ObjectMapper的常用配置
private static final ObjectMapper mapper;
public static ObjectMapper getObjectMapper(){
return this.mapper;
}
static{
mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JavaTimeModule());
}
ObjectMapper的常用方法
mapper.writeValueAsString(xxx.class) 序列化
mapper.readValue(jsonString, xxx.class) 反序列化
json字符串转对象
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Hyl\", \"age\":20}";
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
结果:
Student [ name: Hyl, age: 20 ]
{
"name" : "Hyl",
"age" : 20
}
getFactory() 序列化
JsonGenerator teststringstu = objectMapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
teststringstu.writeObject(student);
System.out.println(teststringstu);
此方法同样可以得到上面方法的值。但是注意此方法中的这个函数:createGenerator() ,它需要两个参数 ,一个是OutputStream 类型参数,一个是JsonEncoding 类型参数。通过这两个参数,我们可以了解到,此方法不仅可以将Json直接写入网络流,还可以将Json写入文件流或者内存流
渐次反序列化
此方法更灵活,可以只将用户感兴趣的Json串信息值提取出来 。主要利用ObjectMapper提供的readTree 和Jackson提供的JsonNode类 来实现
String test="{"results":[{"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.9150390625}]},{"objectID":358,"geoPoints":[{"x":504602.2680053711,"y":305554.43603515625}]}]}";
JsonNode node = objectMapper.readTree(test);
JsonNode contents = node.get("results");
for (int i = 0; i < contents.size(); i++) {
System.out.println(contents.get(i).get("objectID").getIntValue());
JsonNode geoNumber = contents.get(i).get("geoPoints");
for (int j = 0; j < geoNumber.size(); j++) {
System.out.println(geoNumber.get(j).get("x").getDoubleValue() + " " + geoNumber.get(j).get("y").getDoubleValue());
}
}
System.out.println(teststringstu);
输出
357
504604.59802246094 305569.9150390625
358
504602.2680053711 305554.43603515625
此方法类似于XML解析中的DOM方式解析 ,其好处是结构明细 ,便于提取想要的信息。当然,其缺点也和此方法一样:耗时费空间
数组和对象之间转换
byte[] byteArr = mapper.writeValueAsBytes(student);
System.out.println(byteArr);
Student student= mapper.readValue(byteArr, Student.class);
System.out.println(student);
结果:
[B@3327bd23
Student [ name: Hyl, age: 20 ]
集合和json字符串之间转换
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}]
map和json字符串之间转换
Map<String, Object> testMap = new HashMap<>();
testMap.put("name", "22");
testMap.put("age", 20);
testMap.put("date", new Date());
testMap.put("student", new Student("hyl", 20, new Date()));
String jsonStr = mapper.writeValueAsString(testMap);
System.out.println(jsonStr);
Map<String, Object> testMapDes = mapper.readValue(jsonStr, Map.class);
System.out.println(testMapDes);
结果:
{
"date" : 1525164212803,
"name" : "22",
"student" : {
"name" : "hyl",
"age" : 20,
"sendTime" : 1525164212803,
"intList" : null
},
"age" : 20
}
{date=1525164212803, name=22, student={name=hyl, age=20, sendTime=1525164212803, intList=null}, age=20}
日期转json字符串
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
Student student = new Student ("hyl",21, new Date());
student.setIntList(Arrays.asList(1, 2, 3));
String jsonStr = mapper.writeValueAsString(student);
System.out.println(jsonStr);
结果:
{
"name" : "hyl",
"age" : 21,
"sendTime" : "2020-07-23 13:14:36",
"intList" : [ 1, 2, 3 ]
}
把一个对象集合转换为一个 Java里面的数组
public class Main2 {
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
List<Person> personList = Arrays.asList(
Person.builder().age(10).name("张三").list(Arrays.asList("爱吃", "爱喝", "爱玩")).build(),
Person.builder().age(11).name("李四").list(Arrays.asList("爱谁", "爱你", "爱我")).build()
);
String personStr = objectMapper.writeValueAsString(persons);
List<Person> persons2 = objectMapper.readValue(personStr, new TypeReference<List<Person>>() {});
for(Person person : persons2) {
System.out.println(person);
}
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
List<Person> persons3 = objectMapper.readValue(personStr, javaType);
for(Person person : persons3) {
System.out.println(person);
}
}
}
在 impl 实现类中使用 ObjectMapper
当做 bean 注入
@Resource
private ObjectMapper objectMapper;
|