简体   繁体   English

使用 Java 中的 Jackson 处理 JSON 中的原始联合类型(反)序列化

[英]Handle primitive union types in JSON (de)serialization with Jackson in Java

I know that there are a couple of questions around this topic already, but I still struggle to find a good solution for primitive types.我知道围绕这个主题已经有几个问题,但我仍然很难为原始类型找到一个好的解决方案。 I am trying to serialize and deserialize the following JSON data:我正在尝试序列化和反序列化以下 JSON 数据:

{
  "key": "key1"
  "value": "value1"
}

However, the value is a union type and could be either a boolean, a number or a string.但是,该值是联合类型,可以是 boolean、数字或字符串。 So these are also valid inputs:所以这些也是有效的输入:

{
  "key": "key2"
  "value": true
}

and

{
  "key": "key3"
  "value": 3
}

What is the best way to serialize and deserialize this into a Java POJO?将其序列化和反序列化为 Java POJO 的最佳方法是什么? My approach looks like this (but obviously only works with string values)我的方法看起来像这样(但显然只适用于字符串值)

@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
public class Request {

    private final String key;

    private final String value;
}

@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
public class Response {

    private final String key;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private final String value;
}

Solved it this way.就这样解决了。

@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
public class Request {

    private final String key;

    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "valueClass")
    private final String value;

    private final String valueClass;
}

@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
public class Response {

    private final String key;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "valueClass")
    private final String value;

    @JsonIgnore
    private final String valueClass;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM