ObjectMapper的使用
这个类是jackson提供的,主要是用来把对象转换成为一个json字符串返回到前端,现在几乎所有数据交换都是以json来传输的。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。当然这只是其中的一种 后续我还会将介绍比较火的Gson。
首先在pom.xml文件中,加入依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
代码解释
package com.ghl.demo;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ObjectMapperDemo {
public static void main(String[] args) throws Exception {
/*testObj();*/
/*testList();*/
testMap();
}
/**
* 1.对象转json格式的字符串
* 2.对象转字节数组
* 3.json字符串转为对象
* 4.byte数组转为对象
* @throws Exception
*/
public static void testObj() throws Exception {
//创建转换对象 使用默认的构造方法,使用的是JsonParsers和JsonGenerators映射
ObjectMapper mapper=new ObjectMapper();
// 转换为格式化的json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 如果json中存在目标对象Object不存在的字段,则会报错:Unrecognized field xxx
//需要加上下面的语句,才可正常转换DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
//也可以直接在整个类上面加上注解@JsonIgnoreProperties(ignoreUnknown = true)
//下面这个属性默认的是true,即必须要有get方法
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//创建学生对象
Student stu=new Student("ghl", 12, "123", "19845252@qq.com");
//1.对象转json格式的字符串
String stuToString = mapper.writeValueAsString(stu);
//System.out.println("对象转为字符串:" + stuToString);
/*
* 输出结果:
* 对象转为字符串:{
"name" : "ghl",
"age" : 12,
"password" : "123",
"email" : "19845252@qq.com"
}
*/
//2.对象转字节数组
byte[] byteArr = mapper.writeValueAsBytes(stu);
System.out.println("对象转为byte数组:" + byteArr);
/*
* 对象转为byte数组:[B@6aaa5eb0
*/
//3.json字符串转为对象
Student student = mapper.readValue(stuToString, Student.class);
System.out.println("json字符串转为对象:" + student);
//json字符串转为对象:Student [name=ghl, age=12, password=123, email=19845252@qq.com]
//4.byte数组转为对象
Student student2 = mapper.readValue(byteArr, Student.class);
System.out.println("byte数组转为对象:" + student2);
//输出结果:byte数组转为对象:Student [name=ghl, age=12, password=123, email=19845252@qq.com]
mapper.writeValue(new File("D:/test.txt"), stu); // 写到文件中
}
/**list集合与json字符的转换
* 1.集合转为字符串
* 2.字符串转集合
* @throws Exception
*
*/
public static void testList() throws Exception {
//创建转换对象 使用默认的构造方法,使用的是JsonParsers和JsonGenerators映射
ObjectMapper mapper=new ObjectMapper();
// 转换为格式化的json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 如果json中有新增的字段并且是实体类类中不存在的,不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Student> studnetList = new ArrayList<Student>();
studnetList.add(new Student("zs", 12, "121", "1584578878@qq.com"));
studnetList.add(new Student("lisi", 13, "122", "1584578878@qq.com"));
studnetList.add(new Student("wangwu", 14, "123", "1584578878@qq.com"));
studnetList.add(new Student("zhangliu", 15, "124", "1584578878@qq.com"));
//1.集合转为字符串
String jsonStr = mapper.writeValueAsString(studnetList);
System.out.println("集合转为字符串:" + jsonStr);
/*輸出結果
* 集合转为字符串:[ {
"name" : "zs",
"age" : 12,
"password" : "121",
"email" : "1584578878@qq.com"
}, {
"name" : "lisi",
"age" : 13,
"password" : "122",
"email" : "1584578878@qq.com"
}, {
"name" : "wangwu",
"age" : 14,
"password" : "123",
"email" : "1584578878@qq.com"
}, {
"name" : "zhangliu",
"age" : 15,
"password" : "124",
"email" : "1584578878@qq.com"
} ]
*
*/
//2.字符串转集合
List<Student> userListDes = mapper.readValue(jsonStr, List.class);
System.out.println("字符串转集合:" + userListDes);
/*輸出結果
* 字符串转集合:[{name=zs, age=12, password=121, email=1584578878@qq.com},
* {name=lisi, age=13, password=122, email=1584578878@qq.com},
* {name=wangwu, age=14, password=123, email=1584578878@qq.com},
* {name=zhangliu, age=15, password=124, email=1584578878@qq.com}]
*/
}
/**Map与字符串转换
* 1.Map转为字符串
* 2.字符串转Map
* @throws Exception
*/
public static void testMap() throws Exception {
//创建转换对象 使用默认的构造方法,使用的是JsonParsers和JsonGenerators映射
ObjectMapper mapper=new ObjectMapper();
// 转换为格式化的json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 如果json中有新增的字段并且是实体类类中不存在的,不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<String, Object> testMap = new HashMap<String, Object>();
testMap.put("name", "ghl");
testMap.put("age", 18);
//1.Map转为字符串
String jsonStr = mapper.writeValueAsString(testMap);
System.out.println("Map转为字符串:" + jsonStr);
/*
* Map转为字符串:{
"name" : "ghl",
"age" : 18
}
*/
//2.字符串转Map
Map<String, Object> testMapDes = mapper.readValue(jsonStr, Map.class);
System.out.println("字符串转Map:" + testMapDes);
/*
* 字符串转Map:{name=ghl, age=18}
*/
}
}
jsonUtils工具类
POM文件
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.32</version>
</dependency>
json工具类
package com.ghl.demo;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串�??
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T> T getJson(String jsonString, Class<T> cls) {
T t = null;
try {
t = JSON.parseObject(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return t;
}
public static <T> List<T> getArrayJson(String jsonString, Class<T> cls) {
List<T> list = new ArrayList<T>();
try {
list = JSON.parseArray(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
实例如下:
Person 类:
public class Person {
private int id;
private String name;
private String password;
public Person() {
super();
}
public Person(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
/*省略get和set方法*/
}
测试DEMO:
package com.dimple.ObjectMapperDemo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectMapperTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(1, "tom", "123");
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JsonString: " + jsonString);
}
}
JSON对象转为Java对象
public class ObjectMapperTest {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
Person person = new Person(1, "tom", "123");
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JsonString: " + jsonString);
Person person1 = objectMapper.readValue(jsonString, Person.class);
System.out.println(person1.toString());
}
}
Java数组对象和JSON数组对象转换
public class ObjectMapperTest {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
//Java数组转换为JSON数组
Person person = new Person(1, "tom", "123");
Person person1 = new Person(2, "jack", "123445");
List<Person> personList = new ArrayList<>();
personList.add(person);
personList.add(person1);
String jsonString = objectMapper.writeValueAsString(personList);
System.out.println("JsonString List: " + jsonString);
//Json数组转换为Java数组
//JavaType
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
List<Person> list = objectMapper.readValue(jsonString,javaType);
//打印出list中的值
for (Person person2 : list) {
System.out.println(person2.toString());
}
}
}
来源:oschina
链接:https://my.oschina.net/u/2331760/blog/3222865