英文:
Handle primitive union types in JSON (de)serialization with Jackson in Java
问题
我知道关于这个主题已经有一些问题,但我仍然很难找到一个适用于基本类型的好解决方案。我正在尝试对以下JSON数据进行序列化和反序列化:
{
"key": "key1"
"value": "value1"
}
然而,该值是一个联合类型,可以是布尔值、数字或字符串。因此,这些也是有效的输入:
{
"key": "key2"
"value": true
}
和
{
"key": "key3"
"value": 3
}
最佳的方法是如何将其序列化和反序列化为Java POJO?我的方法如下(但显然只适用于字符串值)
@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;
}
英文:
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:
{
"key": "key1"
"value": "value1"
}
However, the value is a union type and could be either a boolean, a number or a string. 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? 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;
}
答案1
得分: 0
这样解决了。
@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;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论