You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jackson/Gson实现@JsonProperty标注字符串与枚举值直接互转

解决方案

Jackson原生方案

Jackson可以直接复用已有的@JsonProperty注解完成转换,不需要额外给枚举新增字段,直接使用ObjectMapper提供的方法即可:

  • 字符串转枚举:调用ObjectMapper#convertValue方法直接将字符串转为枚举对象
  • 枚举转字符串:调用ObjectMapper#valueToTree方法获取序列化后的Json节点,直接取文本值即可

示例代码如下:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public enum Type {
    @JsonProperty("Files")
    File,
    @JsonProperty("Folders")
    Folder;

    // 全局复用同一个ObjectMapper即可,也可直接使用项目中已配置的全局实例
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    // 字符串转枚举
    public static Type fromJsonPropertyStr(String str) {
        return OBJECT_MAPPER.convertValue(str, Type.class);
    }

    // 枚举转JsonProperty标注的字符串
    public String toJsonPropertyStr() {
        return OBJECT_MAPPER.valueToTree(this).asText();
    }
}

使用示例:

Type fileType = Type.fromJsonPropertyStr("Files"); // 得到Type.File
String fileStr = Type.File.toJsonPropertyStr(); // 得到"Files"

Gson原生方案

Gson默认使用@SerializedName注解实现类似功能,如果要复用已有的@JsonProperty注解,可以注册支持Jackson注解的扩展模块。基础实现代码如下:

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public enum Type {
    @SerializedName("Files")
    File,
    @SerializedName("Folders")
    Folder;

    private static final Gson GSON = new Gson();

    // 字符串转枚举
    public static Type fromSerializedNameStr(String str) {
        return GSON.fromJson("\"" + str + "\"", Type.class);
    }

    // 枚举转SerializedName标注的字符串
    public String toSerializedNameStr() {
        return GSON.toJsonTree(this).getAsString();
    }
}

内容的提问来源于stack exchange,提问作者cosimoth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:39:02