我希望将嵌套的JSON结构映射到Jackson,其中对象是动态ID的对象。
{
"id1": {
"prop": true
},
"id2": {
"prop": true
},
"id3": {
"prop": true
}
}
我目前有以下杰克逊POJO:
package com.uk.jacob.containerdroid;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import java.util.HashMap;
import java.util.Map;
public class Container {
private Map<String, ContainerDetails> properties = new HashMap<>();
public class ContainerDetails {
private boolean prop;
public boolean getProp() {
return prop;
}
public void setProp(boolean prop) {
this.prop = prop;
}
}
@JsonAnySetter
public void add(String key, ContainerDetails value) {
properties.put(key, value);
}
@JsonAnyGetter
public Map<String, ContainerDetails> getProperties() {
return properties;
}
@Override
public String toString() {
return "Containers {" +
", properties=" + properties.toString() +
'}';
}
}
适用于静态属性的数据,但不适用于嵌套的JSON。
我收到错误:
12-23 22:32:41.628 14098-14098/? W/System.err﹕ at [Source: { "test": { "prop": true } }; line: 1, column: 13] (through reference chain: com.uk.jacob.containerdroid.models.Container["test"])
如何操作以上内容才能正确映射?
答案 0 :(得分:1)
似乎你只想要一个Map<String, Foo>
,其中Foo被定义为
public class Foo {
private boolean prop;
// getter, setter omitted
}
完整的工作示例:
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Foo {
private boolean prop;
public boolean isProp() {
return prop;
}
public void setProp(boolean prop) {
this.prop = prop;
}
@Override
public String toString() {
return "Foo{" +
"prop=" + prop +
'}';
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{ \n" +
" \"id1\": {\n" +
" \"prop\": true\n" +
" },\n" +
" \"id2\": {\n" +
" \"prop\": true\n" +
" },\n" +
" \"id3\": {\n" +
" \"prop\": true\n" +
" }\n" +
" }";
Map<String, Foo> map = mapper.readValue(json, new TypeReference<Map<String, Foo>>() {
});
System.out.println("map = " + map);
}
}