Jackson的ObjectMapper使用

一、maven依赖

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

jackson包含jackson-databind、jackson-core、jackson-annotations,因为jackson-databind依赖于jackson-core、jackson-annotations,所有pom文件导入jackson-databind依赖即可

二、JavaBean、JSON、JsonNode的转换

public class Student {
    private String name;
    private int age;
    private Date date;

    public Student(){
    }

    public Student(String name, int age, Date date) {
        this.name = name;
        this.age = age;
        this.date = date;
    }
    // set、get方法,toString方法
}

1.JavaBean与JSON的转换

1) 创建ObjectMapper对象  ObjectMapper mapper = new ObjectMapper();
2) 反序列化JSON到对象    Student student = mapper.readValue(jsonString, Student.class);
3) 序列化对象到JSON        String jsonString = mapper.writeValueAsString(student);

@Test
public void testObjectMap() throws JsonProcessingException, ParseException {
    Student student = new Student("迪丽热巴", 28, new SimpleDateFormat("yyyy-MM-dd").parse("1992-06-03"));
    ObjectMapper mapper = new ObjectMapper();
    // JavaBean -> JSON
    String studentJson = mapper.writeValueAsString(student);
    System.out.println(studentJson);
    // JSON -> JavaBean
    Student studentObject = mapper.readValue(studentJson, Student.class);
    System.out.println(studentObject);
}

结果:

2.JSON转换JsonNode

ObjectMapper构建JsonNode节点树

@Test
public void testJsonNode() throws JsonProcessingException, ParseException {
    Student student = new Student("迪丽热巴", 28, new SimpleDateFormat("yyyy-MM-dd").parse("1992-06-03"));
    ObjectMapper mapper = new ObjectMapper();
    String studentJson = mapper.writeValueAsString(student);
    // JSON -> JsonNode
    JsonNode jsonNode = mapper.readTree(studentJson);
    JsonNode name = jsonNode.path("name");
    JsonNode age = jsonNode.path("age");
    System.out.println(name.asText() + " " + age.asInt());
    // 遍历
    Iterator<JsonNode> iterator = jsonNode.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

结果:

三、ObjectMapper配置

1.序列化

  • SerializationFeature.INDENT_OUTPUT 缩进的特性
  • SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 把日期写成时间戳
@Test
public void testSerialization() throws JsonProcessingException, ParseException {
    Student student = new Student("迪丽热巴", 28, new SimpleDateFormat("yyyy-MM-dd").parse("1992-06-03"));
    ObjectMapper mapper = new ObjectMapper();
    // 启用,转换为缩进的json
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    // mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    // 禁止,把java.util.Date, Calendar输出为数字(时间戳)
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    // mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    String studentJson = mapper.writeValueAsString(student);
    System.out.println(studentJson);
}

结果:

2.反序列化

  • DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 未知属性会出现错误
@Test
public void testDeserialization() throws JsonProcessingException {
    //{"name" : "","age" : 28,"gender": "female"}
    String jsonStr = "{\"name\" : \"\",\"age\" : 28,\"gender\": \"female\"}";
    ObjectMapper mapper = new ObjectMapper();
    // 在遇到未知属性的时候不抛出异常
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Student student = mapper.readValue(jsonStr, Student.class);
    System.out.println(student);
}

结果:

3.setSerializationInclusionde的使用

  • Include.ALWAYS  是序列化对象所有属性
  • Include.NON_NULL 只有不为null的字段才被序列化
  • Include.NON_EMPTY 如果为null或者空字符串和空集合都不会被序列化
@Test
public void testSetSerializationInclusionde() throws JsonProcessingException {
    Student student = new Student("迪丽热巴", 28, null);
    ObjectMapper mapper = new ObjectMapper();
    // 只有不为null的字段才被序列化
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    String studentJson = mapper.writeValueAsString(student);
    System.out.println(studentJson);
}

结果:

三、注解

  • @JsonProperty注解指定一个属性用于JSON映射,默认情况下映射的JSON属性与注解的属性名称相同,不过可以使用该注解的value值修改JSON属性名,该注解还有一个index属性指定生成JSON属性的顺序
  • @JsonIgnore注解用于排除某个属性,这样该属性就不会被Jackson序列化和反序列化
  • @JsonIgnoreProperties类注解。在序列化为JSON的时候,@JsonIgnoreProperties({"prop1", "prop2"})会忽略pro1和prop2两个属性。在从JSON反序列化为Java类的时候,@JsonIgnoreProperties(IgnoreUnknow=true)会忽略所有没有Getter和Setter的属性。该注解在Java类和JSON不完全匹配的时候很有用
  • @JsonIgnoreType类注解,会排除所有指定类型的属性
@JsonIgnoreProperties({"date"})
public class Student {

    @JsonProperty(value = "username")
    private String name;
    @JsonIgnore
    private int age;
    private Date date;

    public Student(){
    }

    public Student(String name, int age, Date date) {
        this.name = name;
        this.age = age;
        this.date = date;
    }
    // set、get方法,toString方法
}

测试:

@Test
public void testAnnotation() throws JsonProcessingException, ParseException {
    Student student = new Student("迪丽热巴", 28, new SimpleDateFormat("yyyy-MM-dd").parse("1992-06-03"));
    ObjectMapper mapper = new ObjectMapper();
    String studentJson = mapper.writeValueAsString(student);
    System.out.println(studentJson);
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值