作者:迅驰代驾 | 来源:互联网 | 2024-11-08 13:21
本文介绍了如何利用ObjectMapper实现JSON与JavaBean之间的高效转换。ObjectMapper是Jackson库的核心组件,能够便捷地将Java对象序列化为JSON格式,并支持从JSON、XML以及文件等多种数据源反序列化为Java对象。此外,还探讨了在实际应用中如何优化转换性能,以提升系统整体效率。
ObjectMapper 介绍:
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml、文件等转换成Java对象。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。
Jackson主要包含了3个模块:
jackson-core
jackson-annotations
jackson-databind
其中,jackson-annotations依赖于jackson-core,jackson-databind又依赖于jackson-annotations。
Jackson有三种方式处理Json:
使用底层的基于Stream的方式对Json的每一个小的组成部分进行控制
使用Tree Model,通过JsonNode处理单个Json节点
使用databind模块,直接对Java对象进行序列化和反序列化
通常来说,我们在日常开发中使用的是第3种方式,有时为了简便也会使用第2种方式,比如你要从一个很大的Json对象中只读取那么一两个字段的时候,采用databind方式显得有些重,JsonNode反而更简单。
加入依赖
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.3</version></dependency>
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 {testMap();}public static void testObj() throws Exception {ObjectMapper mapper&#61;new ObjectMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);Student stu&#61;new Student("ghl", 12, "123", "19845252&#64;qq.com");String stuToString &#61; mapper.writeValueAsString(stu);byte[] byteArr &#61; mapper.writeValueAsBytes(stu);System.out.println("对象转为byte数组&#xff1a;" &#43; byteArr);Student student &#61; mapper.readValue(stuToString, Student.class);System.out.println("json字符串转为对象&#xff1a;" &#43; student);Student student2 &#61; mapper.readValue(byteArr, Student.class);System.out.println("byte数组转为对象&#xff1a;" &#43; student2);mapper.writeValue(new File("D:/test.txt"), stu); }public static void testList() throws Exception {ObjectMapper mapper&#61;new ObjectMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);List<Student> studnetList &#61; new ArrayList<Student>();studnetList.add(new Student("zs", 12, "121", "1584578878&#64;qq.com"));studnetList.add(new Student("lisi", 13, "122", "1584578878&#64;qq.com"));studnetList.add(new Student("wangwu", 14, "123", "1584578878&#64;qq.com"));studnetList.add(new Student("zhangliu", 15, "124", "1584578878&#64;qq.com"));String jsonStr &#61; mapper.writeValueAsString(studnetList);System.out.println("集合转为字符串&#xff1a;" &#43; jsonStr);List<Student> userListDes &#61; mapper.readValue(jsonStr, List.class);System.out.println("字符串转集合&#xff1a;" &#43; userListDes);}public static void testMap() throws Exception {ObjectMapper mapper&#61;new ObjectMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);Map<String, Object> testMap &#61; new HashMap<String, Object>();testMap.put("name", "ghl");testMap.put("age", 18);String jsonStr &#61; mapper.writeValueAsString(testMap);System.out.println("Map转为字符串&#xff1a;" &#43; jsonStr);Map<String, Object> testMapDes &#61; mapper.readValue(jsonStr, Map.class);System.out.println("字符串转Map&#xff1a;" &#43; testMapDes);}
}
工具类
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 {private static final ObjectMapper MAPPER &#61; new ObjectMapper();public static String objectToJson(Object data) {try {String string &#61; MAPPER.writeValueAsString(data);return string;} catch (JsonProcessingException e) {e.printStackTrace();}return null;}public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {try {T t &#61; MAPPER.readValue(jsonData, beanType);return t;} catch (Exception e) {e.printStackTrace();}return null;}public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {JavaType javaType &#61; MAPPER.getTypeFactory().constructParametricType(List.class, beanType);try {List<T> list &#61; 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 &#61; null;try {t &#61; JSON.parseObject(jsonString, cls);} catch (Exception e) {e.printStackTrace();}return t;}public static <T> List<T> getArrayJson(String jsonString, Class<T> cls) {List<T> list &#61; new ArrayList<T>();try {list &#61; JSON.parseArray(jsonString, cls);} catch (Exception e) {}return list;}}