java 如何让Jackson用name序列化枚举

hgb9j2n6  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(159)

我想使用Jacksonapi 'com.fasterxml.jackson.core:jackson-databind:2.14.2'序列化对象,代码如下:

WebSocketMsg resp = new WebSocketMsg(MsgType.USER_CHAT,responseMsg );
ObjectMapper objectMapper = new ObjectMapper();
String resultJson= objectMapper.writeValueAsString(resp);

现在序列化WebSocketMsg enum using value,有没有可能使用enum名称来使其序列化?这是enum定义:

@Schema(implementation = MsgType.class)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MsgType {
    HEARTBEAT(1, "heartbeat")
}

我尝试添加@JsonFormat(shape = JsonFormat.Shape.OBJECT),但仍然无法工作。这是WebSocketMsg定义:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebSocketMsg {
    private MsgType msgType;
    private String msg;
}

我想要的json可能看起来像:

{
msgType: "HEARTBEAT",
msg: "balabala....."
}
a7qyws3x

a7qyws3x1#

如果你删除@JsonFormat(shape = JsonFormat.Shape.OBJECT),你会得到想要的格式:

@Test
void test() throws JsonProcessingException {
    WebSocketMsg resp = new WebSocketMsg(MsgType.HEARTBEAT, "test-msg");

    ObjectMapper objectMapper = new ObjectMapper();
    String resultJson = objectMapper.writeValueAsString(resp);

    assertThat(resultJson).isEqualToIgnoringWhitespace("""
        {
            "msgType":"HEARTBEAT",
            "msg":"test-msg"
        }
        """);
}

但是,如果你保留这个注解,enum将像一个对象一样显示。因此,结果json将是:

{
    "msgType": {
        "nr":1,
        "value":"heartbeat"
    },
    "msg":"test-msg"
}

相关问题