1. 入门案例
package com.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestObjectMapper {
/**
* 1.通过测试类 实现对象与JSON之间的转化
* 重点常识:
* 1.对象转化JSON 获取所有的getXXX()办法~~~~去除get~~~~~首字母小写~~造成属性
* 2.JSON转化为对象 利用Class的反射机制实例化对象~~~~获取json中的属性
* ~~~~拼接setXXX办法~~~~~调用对象的setXXX(arg)办法为对象赋值 */
@Test
public void test01() throws JsonProcessingException {
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("转化测试").setCreated(new Date());
ObjectMapper objectMapper = new ObjectMapper();
//1.将对象转化为JSON
String json = objectMapper.writeValueAsString(itemDesc);
System.out.println(json);
//2.将JSON转化为对象 反射思维
ItemDesc itemDesc2 = objectMapper.readValue(json, ItemDesc.class);
System.out.println(itemDesc2.getCreated());
}
// 汇合 转 json
@Test
public void testList() throws JsonProcessingException {
List<ItemDesc> list = new ArrayList<>();
list.add(new ItemDesc().setItemId(100L).setItemDesc("案例1"));
list.add(new ItemDesc().setItemId(100L).setItemDesc("案例1"));
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(list);
System.out.println(json);
List list2 = objectMapper.readValue(json, list.getClass());
System.out.println(list2);
}
}
2. 封装ObjectMapperUtil
package com.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
public class ObjectMapperUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
//1.对象转化为JSON
public static String toJSON(Object obj){
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
//将查看异样.转化为运行时异样 之后被全局异样解决机制解决
e.printStackTrace(); //日志打印....
throw new RuntimeException(e);// 抛出运行时异样,交给本人写好的全局异样解决
}
}
//2.JSON转化为对象 用户指定什么样的类型,返回什么样的对象????
// 传什么就返回什么---用泛型来实现 <T> 示意定义泛型,java中先定义,后应用
public static <T> T toObj(String json,Class<T> target){
try {
return MAPPER.readValue(json, target);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
发表回复