Jackson 的核心模块由三部分组成。
- jackson-core,核心包,提供基于”流模式”解析的相关 API,它包括 JsonPaser 和 JsonGenerator。
Jackson 内部实现正是通过高性能的流模式 API 的 JsonGenerator 和 JsonParser 来生成和解析 json。 - jackson-annotations,注解包,提供标准注解功能;
- jackson-databind ,数据绑定包, 提供基于”对象绑定” 解析的相关 API ( ObjectMapper ) 和”树模型” 解析的相关 API (JsonNode);基于”对象绑定” 解析的 API 和”树模型”解析的 API 依赖基于”流模式”解析的 API。
ObjectMapper
Jackson 最常用的 API 就是基于”对象绑定” 的 ObjectMapper。下面是一个 ObjectMapper 的使用的简单示例。
案例
新的springboot内嵌啦,可不用添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
导包 com.fasterxml.jackson.databind
ObjectMapper
简单对象的转化
@Test
public void test01() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("商品详情信息")
.setCreated(new Date()).setUpdated(new Date());
//对象转化为json
String json = objectMapper.writeValueAsString(itemDesc);
System.out.println(json);
//json转化为对象
ItemDesc itemDesc2 = objectMapper.readValue(json, ItemDesc.class);
System.out.println(itemDesc2.getItemDesc());
}
测试集合对象的转化
@Test
public void test02() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("商品详情信息1")
.setCreated(new Date()).setUpdated(new Date());
ItemDesc itemDesc2 = new ItemDesc();
itemDesc2.setItemId(100L).setItemDesc("商品详情信息2")
.setCreated(new Date()).setUpdated(new Date());
List<ItemDesc> lists = new ArrayList<>();
lists.add(itemDesc);
lists.add(itemDesc2);
//[{key:value},{}]
String json = objectMapper.writeValueAsString(lists);
System.out.println(json);
//将json串转化为对象
List<ItemDesc> list2 = objectMapper.readValue(json, lists.getClass());
System.out.println(list2);
}
编辑工具API
package com.jt.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.springframework.util.StringUtils;
public class ObjectMapperUtil {
/**
* 1.将用户传递的数据转化为json串
* 2.将用户传递的json串转化为对象
*/
private static final ObjectMapper MAPPER = new ObjectMapper();
//1.将用户传递的数据转化为json串
public static String toJSON(Object object){
if(object == null) {
throw new RuntimeException("传递的数据为null.请检查");
}
try {
String json = MAPPER.writeValueAsString(object);
return json;
} catch (JsonProcessingException e) {
//将检查异常,转化为运行时异常
e.printStackTrace();
throw new RuntimeException(e);
}
}
//需求: 要求用户传递什么样的类型,我返回什么样的对象 泛型的知识
public static <T> T toObj(String json,Class<T> target){
if(StringUtils.isEmpty(json) || target ==null){
throw new RuntimeException("参数不能为null");
}
try {
return MAPPER.readValue(json, target);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
1.对象转化为json
String json =objectMapper.writeValueAsString(object);
2.json串转化为对象
Object object=objectMapper.readValue(json, Object.class);