jackson 快速开始

jackson 介绍

官方地址: https://github.com/FasterXML/jackson-core

常用使用方法

maven引入

<properties>
        <jackson-version>2.9.9</jackson-version>
    </properties>
    ...
    
    <dependencyManagement>
        <dependencies>
            <!--jackson-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson-version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson-version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson-version}</version>
            </dependency>

JAVA对象转JSON[JSON序列化]

ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。

ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。

  1. writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
  2. writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
  3. writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
  4. writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。

JSON转Java类[JSON反序列化]

JSON转对象

objectMapping.readValue(str, ojb.class)
  • 如果json字符串中的属性个数小于java对象中的属性个数,可以顺利转换,java中多的那个属性为null

  • 如果json字符串中出现java对象中没有的属性,则在将json转换为java对象时会报错:Unrecognized field, not marked as ignorable

demo

public class JacksonTest {
    public static void main(String args[]) {


        Student student = new Student();
        student.setAge(20);
        student.setName("she");

        ObjectMapper mapper = new ObjectMapper();
        try {
            //Java类转JSON
            String json = mapper.writeValueAsString(student);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        //Java集合转JSON
        List<Student> studentList = new ArrayList<Student>();
        studentList.add(student);
        String jsonlist = null;
        try {
            jsonlist = mapper.writeValueAsString(studentList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println(jsonlist);


        String json = "{\"name\":\"she\",\"age\":20}";

        /**
         * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
         */
        ObjectMapper mapper1 = new ObjectMapper();
        Student student1 = null;
        try {
            student1 = mapper1.readValue(json, Student.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(student1);

    }

    static class Student {
        private String name;
        private int age;

        public Student() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }


    }
}

SpringBoot Jackson

SpringBoot JSON工具包默认是Jackson,只需要引入spring-boot-starter-web依赖包,自动引如下相应依赖包:

<dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-databind</artifactId> -->数据绑定依赖于下面两个包

        <version>2.8.7</version>

</dependency>

<dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-annotations</artifactId> -->注解包

        <version>2.8.0</version>

</dependency>

<dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-core</artifactId> -->核心包

        <version>2.8.7</version>

</dependency>

Jackson两种配置方式

  1. application.properties文件
# 日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# 日期时区
spring.jackson.time-zone=GMT+8
# 返回值null不显示
spring.jackson.default-property-inclusion=non_null
  1. bean配置
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfig {

   @Bean
   @Primary
   @ConditionalOnMissingBean(ObjectMapper.class)
   public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
      ObjectMapper objectMapper = builder.createXmlMapper(false).build();
      // 返回值过滤null或""值
      objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY).setSerializationInclusion(JsonInclude.Include.NON_NULL);

      return objectMapper;
   }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章