@JsonValue的用法

jackson学习-JSON相关注解

在实际开发过程中对于对象转json有很多的工具类,这里使用的是jackson

springboot 中jackson的用法

1 springboot工程本身就集成了jackson 只要是引入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

这个pom的可以直接使用
springboot @RestContorller 注解转化json 底层使用的也是jackson

2 其他工程使用jackson主要引入的pom

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.6</version>
        </dependency>

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

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

实际上只要引入pom

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

就可以了包含了其他两个包

一、对于枚举转化为json

1 在项目中经常使用到枚举,对于枚举如果我们不做处理直接转化为json

public enum FlagDeleteEnum implements CommonEnum {

    NO(0, "未删除"), YES(1, "已删除");
    final int code;
    final String msg;

    FlagDeleteEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }
   // @JsonValue
    public String getMsg() {
        return msg;
    }

    public static FlagDeleteEnum valueOf(int code) {
        return CommonEnum.valueOf(FlagDeleteEnum.class, code);
    }
}

测试

结果

 

 

可以看到只显示枚举NO 并不是需要的实际code 或者是msg

2 当把@JsonValue 注释放开后 实际输出的结果是

 

 

ps:只要在想要属性的get方法上使用@JsonValue 就可以在转化成json的时候获取需要的值

二 、对象转化为json
1 对象的使用跟枚举是一样的
在需要的属性的get方法上添加@JsonValue 那么就可以在转化成json获取自己需要的值

ps:这里暂时只做过一个类使用一个@JsonValue注解的场景
@JsonValue 更多的是想Map中获取key-value中某一个的操作

三、JSON其他注解
Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)。
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty(“name”)。

 

 测试结果

posted @ 2022-09-17 17:08  石三爷  阅读(1429)  评论(0编辑  收藏  举报