ObjectMapper类

前言

ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。

使用

使用Jackson,首先需要相关的jar包。对于使用maven的,需要添加以下依赖:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.5</version>
</dependency>

同时,也可以直接下载Jar包。

点我直达

当然了,也可以通过maven的仓库,然后选择jar包下载。

点我直达

实例演示

Java对象转换为JSON对象


ObjectMapper objectMapper = new ObjectMapper();  

        //序列化的时候序列对象的所有属性  
        objectMapper.setSerializationInclusion(Include.ALWAYS);  

        //反序列化的时候如果多了其他属性,不抛出异常  
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  

        //如果是空对象的时候,不抛异常  
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  

        //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式  
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);  
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))  

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);

    }

}

运行截图如下:
QQ截图20180612215912

可以看到,使用Jackson类就可以将Java对象转换为Json对象。

PS:还需要注意,如果ObjectMapper的configure设置FAIL_ON_EMPTY_BEANS为false,那么对应的实体类的属性没有get方法也不会抛出异常,但是这个属性默认的是true,即必须要有get方法,这个需要注意。

错误如图:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.dimple.ObjectMapperDemo.Person and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

QQ截图20180612221201

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());

    }

}

结果如图:

QQ截图20180612221454

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());
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_32454537/article/details/80672191