Jackson 各种注解使用示例

参考资料

  1. Jackson使い方メモ


一. @JsonIgnore

  • 在序列化和反序列化 JSON 数据时,忽略指定的属性。
import com.fasterxml.jackson.annotation.*;
import lombok.Data;

@Data
public class Test34Entity {

    @JsonIgnore
    private String id;

    private String name;

    private String content;
}
  • 返回数据给前台
@PostMapping("/get_data")
public ResponseEntity<Test34Entity> getData(@RequestBody Test34Entity data) {

    Test34Entity entity  = new Test34Entity();
	
	// 在此处设定了id属性
    entity.setId("1355930");
    entity.setName("贾飞天");
    entity.setContent("内容");

    return ResponseEntity.ok(entity);
}

⏹由于给id属性添加了@JsonIgnore注解,所以id并没有返回给前台。

在这里插入图片描述


二. @JsonIgnoreProperties

  • 同时指定多个需要忽略的属性
import com.fasterxml.jackson.annotation.*;
import lombok.Data;

@Data
@JsonIgnoreProperties({"id", "content"})
public class Test34Entity {

    private String id;

    private String name;

    private String content;
}

⏹可以看到,因为id和content属性被忽略,所以只有name属性被返回到了前台。

在这里插入图片描述


三. @JsonProperty

3.1 作用于entity属性上,指定json对象属性名

⏹由下图可知,当前台json的属性值和后台实体类属性值不匹配时,可使用@JsonProperty指定

在这里插入图片描述

3.2 作用于entity方法上,指定json对象属性名

⏹部分属性值,后台需要根据既存的属性经过业务判断处理后返回前台,且该属性值最终只有前台需要,后台的业务逻辑中并不需要,此时可以将@JsonProperty注解作用于方法上,用来指定该属性

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.util.Optional;

@Data
public class Test34Entity {

    private String firstName;

    private String lastName;
	
	// 后台不需要该属性,只有前台才需要此属性
	// private String fullName;
	
	// 指定该方法的返回值作为json的属性,属性名为fullname
    @JsonProperty("fullName")
    private String getFullName() {
        return Optional.ofNullable(this.firstName).orElse("") + Optional.ofNullable(this.lastName).orElse("");
    }
}

⏹如下图所示,在返回给前台的时候,fullName也被返回。

在这里插入图片描述


四. @JsonFormat

4.1 日期格式化

  • 在Date和YearMonth属性上指定日期字符串的格式
import com.fasterxml.jackson.annotation.*;
import lombok.Data;

import java.time.YearMonth;
import java.util.Date;

@Data
public class Test34Entity {

    @JsonFormat(pattern = "yyyy/MM/dd")
    private Date birthday;

    @JsonFormat(pattern = "yyyy/MM")
    private YearMonth yearMonth;
}

⏹由下图可知,日期字符串转换为java实体类中的日期属性类型

在这里插入图片描述

4.2 数字格式化

  • 指定序列化时的数据类型(返回前台的数据类型)
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.math.BigDecimal;

@Data
public class Test34Entity {
    
    // 指定序列化时的数据类型是字符串
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private BigDecimal num1;

    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private Integer num2;
    
    // 未指定序列化时的数据类型
    private BigDecimal num3;

    private Integer num4;
}

⏹可以看到,指定了 @JsonFormat(shape = JsonFormat.Shape.STRING)注解的属性,返回前台时的数据类型变为字符串类型。

在这里插入图片描述

4.3 枚举类返回code

详情请参考 5.3 后台枚举类型的数据返回给前台

五. @JsonCreator注解 枚举类接收前台提交数据

5.1 枚举类和接收数据entity的定义

⏹定义一个枚举类

  • Jackson根据@JsonCreator注解所作用的枚举类中的方法,将前台提交的数据转换为枚举类对象
  • fromName方法只是为了根据枚举类的name获取枚举类对象,和枚举类序列化反序列化没有关系
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Arrays;

public enum SexTypes {
    男性("1"),
    女性("2"),
    保密("3");
    
    private String code;

    SexTypes(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    /*
    	根据code获取枚举类对象
    	SpringBoot在将前台数据封装的时候,通过@JsonCreator注解对应的方法
    	指定前台的性别code转换为对应的枚举类
	*/ 
    @JsonCreator
    public static SexTypes fromCode(String code) {
        return Arrays.stream(SexTypes.values())
                .filter(item -> item.code.equals(code)).findAny().orElse(null);

    }

    public static SexTypes fromName(String name) {
        return Arrays.stream(SexTypes.values())
                .filter(item -> item.name().equals(name)).findAny().orElse(null);
    }
}

⏹用来接收前台提交到后台数据的entity

import com.example.jmw.common.enums.SexTypes;
import lombok.Data;

@Data
public class Test34Entity {

    private String id;
	
	// 自定义的枚举类
    private SexTypes sexTypes;
}

5.2 后台枚举类接收前台的数据

在这里插入图片描述

5.3 后台枚举类型的数据返回给前台

⏹在不做任何配置的情况下,默认返回前台的数据是枚举类的名称

在这里插入图片描述
⏹在枚举类上配置@JsonFormat(shape = JsonFormat.Shape.OBJECT),返回给前台的是枚举类的code

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SexTypes {
    男性("1"),
    女性("2"),
    保密("3");
	
	// ...以下代码省略...
	
	@JsonCreator
    public static SexTypes fromCode(String code) {
        return Arrays.stream(SexTypes.values())
                .filter(item -> item.code.equals(code)).findAny().orElse(null);
    }
}

⏹效果如下所示,返回的是枚举类的code

在这里插入图片描述


六. @JsonAlias

  • 作用于实体类的属性上
  • 被标记的属性可以同时接受多个指定的key
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Data;

@Data
public class Test34Entity {
	
	// id 和 userId 都将被封装到此处
    @JsonAlias({"userId"})
    private String id;
    
    @JsonAlias({"userName"})
    private String name;
}

⏹效果如下所示,前台json中的key是userId,后台entity的属性值是id,但是通过@JsonAlias注解指定了别名userId,所以成功接受到数据。

在这里插入图片描述

七. @JsonInclude

  • JsonInclude.Include.NON_NULL:指定返回的数据中仅包含非null的数据
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Test34Entity {

    private String id;

    private String name;

    private String content;
}

⏹由下图可知,content属性为null,但是因为通过@JsonInclude(JsonInclude.Include.NON_NULL)的指定,所以值为null的属性压根就没有返回到前台。

在这里插入图片描述

  • 16
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当然,我可以为您提供一个Java使用Jackson实现多态解析JSON示例。这里是一个基本的示例代码: ``` public class Animal { public String name; public String type; } @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type" ) @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat"), }) public abstract class AnimalMixin { @JsonCreator public AnimalMixin(@JsonProperty("name") String name) { } } public class Dog extends Animal { public String breed; public Dog() {} public Dog(String name, String breed) { this.name = name; this.breed = breed; this.type = "dog"; } } public class Cat extends Animal { public int age; public Cat() {} public Cat(String name, int age) { this.name = name; this.age = age; this.type = "cat"; } } public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String json = "{ \"name\": \"Fido\", \"type\": \"dog\", \"breed\": \"beagle\" }"; Animal animal = mapper.readValue(json, Animal.class); System.out.println(animal.name); System.out.println(((Dog)animal).breed); } ``` 在这个示例中,我们有一个Animal类,它有一个name属性和一个type属性。type属性用于标识动物的类型,它将在JSON解析期间用于决定将JSON转换为哪个子类。我们通过@JsonTypeInfo注释和@JsonSubTypes注释来指示Jackson使用多态解析JSON。@JsonTypeInfo注释告诉Jackson使用"type"属性来确定JSON应该被反序列化为哪个类。@JsonSubTypes注释告诉Jackson哪些子类需要被考虑。 我们还有一个AnimalMixin抽象类,它用于处理将JSON转换为适当的子类。在这个例子中,我们有两个实现:Dog和Cat。两个类都有它们自己的属性,但都继承自Animal类。 在main方法中,我们首先创建一个ObjectMapper对象,然后使用readValue方法将JSON字符串转换为Animal对象。然后我们打印了Animal对象的name属性和子类特有的属性。 这是一个Java使用Jackson实现多态解析JSON的基本示例。我希望它能帮助您。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值