【发布时间】:2022-01-21 03:13:54
【问题描述】:
我正在使用 jackson 为 json 序列化/反序列化编写带注释的模型类。
我有一个包含映射的 json,其中键是枚举,值可以是不同的类型(包括数组),具体取决于键值。
一个简化的例子,这就是我需要的:
{
"key1": "string value",
"key2": [{"id":"1", "value": "test1"}, {"id":"2", "value": "test2"}]
}
我试过了,我明白了:
{
"KEY1": {"value": "string value"},
"KEY2": {"list": [{"id": "1", "value": "test1"}, {"id": "2", "value": "test2"}]}
}
所以,解包不起作用。
谁能告诉我我做错了什么?
代码如下:
public class Main {
public static void main(String[] args) throws Exception {
HashMap<Keys, ValueType> map = new HashMap<>();
map.put(Keys.KEY1, new StringValue("string value"));
map.put(Keys.KEY2, new ListValue( Arrays.asList(new Element[] {
new Element("1", "test1"),
new Element("2", "test2")
} )));
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(map);
System.out.println(s);
}
}
public enum Keys {
KEY1("key1"),
KEY2("key2");
private String value;
Keys(String s) {
this.value = s;
}
}
public interface ValueType {
}
public class StringValue implements ValueType {
@JsonUnwrapped
private String value;
public StringValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class ListValue implements ValueType {
@JsonUnwrapped
private List<Element> list;
public ListValue(List<Element> list) {
this.list = list;
}
public List<Element> getList() {
return list;
}
public void setList(List<Element> list) {
this.list = list;
}
}
public class Element {
@JsonProperty
private String id;
@JsonProperty
private String value;
public Element(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
【问题讨论】: