其他分享
首页 > 其他分享> > ObjectMapper使用详细介绍

ObjectMapper使用详细介绍

作者:互联网

ObjectMapper使用详细介绍

1.简介

ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。它可以帮助我们快速的进行各个类型和Json类型的相互转换。可以使用ObjectMapper进行json和对象间的转换

Jackson ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)是使用Jackson解析JSON最简单的方法。
Jackson ObjectMapper可以从字符串、流或文件解析JSON,并创建Java对象或对象图来表示已解析的JSON
将JSON解析为Java对象也称为从JSON反序列化Java对象
Jackson ObjectMapper也可以从Java对象创建JSON. 从Java对象生成JSON的过程也被称为序列化Java对象到JSON

2.依赖:

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

3.ObjectMapper的常用配置

 
private static final ObjectMapper mapper;
 
public static ObjectMapper getObjectMapper(){
    return this.mapper;
}
 
static{
    //创建ObjectMapper对象
    mapper = new ObjectMapper()
 
    //configure方法 配置一些需要的参数
    // 转换为格式化的json 显示出来的格式美化
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
 
   //序列化的时候序列对象的那些属性  
   //JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化 
   //JsonInclude.Include.ALWAYS      所有属性
   //JsonInclude.Include.NON_EMPTY   属性为 空(“”) 或者为 NULL 都不序列化 
   //JsonInclude.Include.NON_NULL    属性为NULL 不序列化
   mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);  
 
   
    //反序列化时,遇到未知属性会不会报错 
    //true - 遇到没有的属性就报错 false - 没有的属性不会管,不会报错
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
    //如果是空对象的时候,不抛异常  
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
 
    // 忽略 transient 修饰的属性
    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());
 
}

4.ObjectMapper的常用方法

1、字符串转实体类

    /**
     * 字符串转实体类
     *
     * @param mapper
     * @param jsonString
     */
    public static void stringToStudent(ObjectMapper mapper, String jsonString) {
        jsonString = "{\"id\":1001,\"name\":\"Tom\",\"info\":\"一个小男孩\"}";

        try {
            Student student = mapper.readValue(jsonString, Student.class);
            System.out.println("student = " + student);
            //student = JacksonTest.Student(id=1001, name=Tom, info=一个小男孩)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、实体类转字符串

    /**
     * 实体类转字符串
     *
     * @param mapper
     * @param jsonString
     */
    public static void studentToString(ObjectMapper mapper, String jsonString) {

        Student student = new Student();
        student.setId(1002);
        student.setName("李四");
        student.setInfo("一个小女孩");
        try {
            jsonString = mapper.writeValueAsString(student);
            System.out.println("jsonString = " + jsonString);
            //jsonString = {"id":1002,"name":"李四","info":"一个小女孩"}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3、字符串转 List<实体类>

/**
     * 字符串转 List<实体类>
     *
     * @param mapper
     * @param jsonString
     */
    public static void stringToStudentList(ObjectMapper mapper, String jsonString) {
        jsonString = "[{\"id\":1001,\"name\":\"Tom\",\"info\":\"一个小男孩\"},{\"id\":1002,\"name\":\"Jane\",\"info\":\"一个小女孩\"}]";
        try {
            Student[] stu = mapper.readValue(jsonString, Student[].class);
            for (Student student : stu) {
                System.out.println("student = " + student);
                //student = JacksonTest.Student(id=1001, name=Tom, info=一个小男孩)
                //student = JacksonTest.Student(id=1002, name=Jane, info=一个小女孩)
            }

            String ss = mapper.writeValueAsString(stu);
            System.out.println("ss = " + ss);
            //ss = [{"id":1001,"name":"Tom","info":"一个小男孩"},{"id":1002,"name":"Jane","info":"一个小女孩"}]

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4.json字符串转对象

ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Hyl\", \"age\":20}";
 
//将字符串转换为对象
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
 
//将对象转换为json字符串
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
 
 
结果:
Student [ name: Hyl, age: 20 ]
 
{
  "name" : "Hyl",
  "age" : 20
}

5.数组和对象之间转换

//对象转为byte数组
byte[] byteArr = mapper.writeValueAsBytes(student);
System.out.println(byteArr);
 
 
//byte数组转为对象
Student student= mapper.readValue(byteArr, Student.class);
System.out.println(student);
 
结果:
[B@3327bd23
 
Student [ name: Hyl, age: 20 ]

6.集合和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}]

7.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}

8.日期转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 ]
}

9.readTree()方法

​ 此方法更灵活,可以只将用户感兴趣的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}]}]}";
 
//此Json串比较复杂,包含了嵌套数组的形式,具有通用性。
 
//2.2.2.2实现反序列化
JsonNode node= objectMapper.readTree(test);      //将Json串以树状结构读入内存
 
JsonNode contents=node.get("results");//得到results这个节点下的信息
 
for(int i=0;i<contents.size();i++)  //遍历results下的信息,size()函数可以得节点所包含的的信息的个数,类似于数组的长度
 
{
 
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());
 
}
 
}
 

参考:

https://blog.csdn.net/u011213044/article/details/120329436

https://blog.csdn.net/weixin_43811057/article/details/124584279

标签:详细,name,mapper,介绍,student,Student,new,ObjectMapper
来源: https://www.cnblogs.com/javaxubo/p/16583980.html