Spring Boot Controller 对于枚举类型的处理

Spring Boot Jackson JSON About 1,774 words

示例

Controller

@GetMapping("/test")
public Object test() {
    return Result.SUCCESS;
}

Enum

@Getter
public enum Result {

    SUCCESS(0, "request_success"),
    FAIL(1, "request_fail");

    private final int code;

    private final String msg;

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

}

原始值

不做任何配置,则会返回枚举的原始字段

"SUCCESS"

对象形式

配置 @JsonFormat

在枚举类上添加@JsonFormat注解,以JsonFormat.Shape.OBJECT对象形式返回。

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@Getter
public enum Result {

    SUCCESS(0, "request_success"),
    FAIL(1, "request_fail");

    private final int code;

    private final String msg;

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

}

返回值示例

{
"code": 0,
"msg": "request_success"
}

映射值

配置 @JsonValue

添加@JsonValue,返回枚举字段中的映射值。

@Getter
public enum Result {

    SUCCESS(0, "request_success"),
    FAIL(1, "request_fail");

    private final int code;

    @JsonValue
    private final String msg;

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

}

返回值

"request_success"

异常情况

错误日志

DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: 
Could not write JSON: Problem with definition of [AnnotedClass com.example.controller.Result]: Multiple 'as-value' properties defined ([field com.example.controller.Result#code] vs [field com.example.controller.Result#value])]

错误原因

配置了多个@JsonValue

@Getter
public enum Result {

    SUCCESS(0, "request_success"),
    FAIL(1, "request_fail");

    @JsonValue
    private final int code;

    @JsonValue
    private final String msg;

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

}
Views: 189 · Posted: 2024-09-13

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh