最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jackson - Annotation to specify value to write for enum in Kotlin - Stack Overflow

programmeradmin3浏览0评论

What's the canonical way to get the following enum to write the intValue when mapping this to a String with a normal ObjectMapper? As-is, it writes the text (for example DEBUG) but I want it to write a 1 (JSON number).

enum class SEVERITY(val intValue: Int) {
    DEBUG(1),
    VERBOSE(2),
    INFO(3),
    WARN(4),
    ERROR(5),
    CRITICAL(6)
}

What's the canonical way to get the following enum to write the intValue when mapping this to a String with a normal ObjectMapper? As-is, it writes the text (for example DEBUG) but I want it to write a 1 (JSON number).

enum class SEVERITY(val intValue: Int) {
    DEBUG(1),
    VERBOSE(2),
    INFO(3),
    WARN(4),
    ERROR(5),
    CRITICAL(6)
}
Share Improve this question edited Mar 17 at 12:39 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 17 at 12:32 mikebmikeb 11.4k8 gold badges69 silver badges132 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Based on this answer, you can annotate a method with @JsonValue that returns an Int, and Jackson will use the return value of that method to write the JSON.

In this case, that method will be the getter for intValue, which you can annotate like this:

enum class Severity(@get:JsonValue val intValue: Int) { ... }

You can also omit "get:", in which case the annotation will be applied to the backing field of intValue, which also works.

发布评论

评论列表(0)

  1. 暂无评论