我的JSON结构如下:
{
"id" : "123",
"name" : [ {
"stuff" : [ {
"id" : "234",
"name" : "Bob"
}, {
"id" : "345",
"name" : "Sally"
} ]
} ]
}
我想要映射到以下数据结构:
MyInterface1
@Value.Immutable
@JsonSerialize(as = ImmutableMyInterface1.class)
@JsonDeserialize(as = ImmutableMyInterface1.class)
public interface MyInterface1 {
String id();
@JsonDeserialize(using = MyInterface1Deserializer.class)
List<MyInterface2> name();
}
MyInterface2
@Value.Immutable
@JsonSerialize(as = ImmutableMyInterface2.class)
@JsonDeserialize(as = ImmutableMyInterface2.class)
public interface MyInterface2 {
@JsonDeserialize(using = StuffDeserializer.class)
Map<String, MyInterface3> stuff();
}
MyInterface3
@Value.Immutable
@JsonSerialize(as = ImmutableMyInterface3.class)
@JsonDeserialize(as = ImmutableMyInterface3.class)
public interface MyInterface3 {
String id();
String name();
}
我使用带有readValue(stringWithJson,MyInterface1.class)
的ObjectMapper将此JSON映射到MyInterface1,它应该从链接到MyInterface3。当我在MyInterface2中使用List时,此设置正常工作,即List<MyInterface3> name();
但是,我希望这是一张地图而不是一张清单,理想情况下是&#34; id&#34;从内部JSON作为关键。这将允许我使用以下语法获取值:
MyInterface1.get(0).MyInterface2.get("id1").name();
问题是,在尝试创建自定义StuffDeserializer.class时,我收到错误:
Can not deserialize instance of com.foo.ImmutableMyInterface2$Json out of START_ARRAY token
尝试时:
public Map<String, MyInterface3> deserialize(JsonParser jsonParser, DeserializationContext ctxt)
throws IOException {
MyInterface2 foo = Unmarshaller.OBJECT_MAPPER.readValue(jsonParser, MyInterface2.class); // error here
...
我认为这是因为杰克逊期待&#34;东西&#34;成为JSON数组的List&#39;原因。将此JSON反序列化为使用内部JSON中的值作为键的映射的最佳方法是什么?
答案 0 :(得分:1)
我会创建一个自定义JsonDeserializer
来将id
和name
映射到地图中:
public class StringHashMapValueDeserializer extends JsonDeserializer<HashMap<String, String>>{
@Override
public HashMap<String, String> deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
HashMap<String, String> ret = new HashMap<String, String>();
ObjectCodec codec = parser.getCodec();
TreeNode node = codec.readTree(parser);
if (node.isArray()){
for (JsonNode n : (ArrayNode)node){
JsonNode id = n.get("id");
if (id != null){
JsonNode name = n.get("name");
ret.put(id.asText(), name.asText());
}
}
}
return ret;
}
}
然后我会使用反序列化器创建带有注释stuff
属性的简单bean:
@Getter
@Setter
public class Name {
@JsonDeserialize(using = StringHashMapValueDeserializer.class)
Map<String, String> stuff;
@Override
public String toString() {
return "Name [stuff=" + stuff + "]";
}
}
外型:
@Getter
@Setter
public class OuterType {
String id;
List<Name> name;
@Override
public String toString() {
return "OuterType [id=" + id + ", stuff=" + name + "]";
}
}
反序列化:
ObjectMapper mapper = new ObjectMapper();
OuterType response;
response = mapper.readValue(json, OuterType.class);
System.out.println(response);
System.out.println(response.getName().get(0).getStuff().get("234"));
控制台输出:
OuterType [id=123, stuff=[Name [stuff={234=Bob, 345=Sally}]]]
Bob
希望它有所帮助。