Jackson将JSON解析为Map< String,TypeA> [英] Jackson parse JSON to Map<String, TypeA>
问题描述
我有以下JSON:
{
"data": {
"1": {
"id":"1",
"name":"test1"
},
"2": {
"id":"2",
"name":"test2"
}
}
}
我想用Jackson将数据"解析为一个对象.如果我将其解析为Map<String, Object>
,则效果很好,而将"1","2"(...)用作Key,并将相应数据作为值,再次由Map表示.
I want to parse the "data" into an Object with Jackson. If I parse it as Map<String, Object>
it works well, whereas "1", "2" (...) are used as Key with the respective data as value, represented by a Map again.
现在我想将此JSON解析为Map<String, TypeA>
,而类TypeA
将具有两个字段,即id和name.
Now I want to parse this JSON to Map<String, TypeA>
whereas class TypeA
would have two fields, id and name.
有人可以给我提示如何做到这一点吗? 我总是收到以下错误:
Can someone give me a hint how to to that? I always get the following error:
无法读取JSON:找不到类型[简单的合适的构造函数 类型,类TypeA]:无法从JSON对象实例化(需要 添加/启用类型信息?)
Could not read JSON: No suitable constructor found for type [simple type, class TypeA]: can not instantiate from JSON object (need to add/enable type information?)
非常感谢,
鞋
Thanks a lot in advance,
tohoe
推荐答案
以下应为您解决.
public class MyDataObject {
private final Map<String, TypeA> data;
@JsonCreator
public MyDataObject(@JsonProperty("data") final Map<String, TypeA> data) {
this.data = data;
}
public Map<String, TypeA> getData() {
return data;
}
}
public class TypeA {
private final String id;
private final String name;
@JsonCreator
public TypeA(@JsonProperty("id") final String id,
@JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
@JsonCreator
用于描述如何创建对象以及属性@JsonProperty
的名称.即使它们是嵌套的.
The @JsonCreator
is used for describing how to create your objects together with the name of the properties @JsonProperty
. Even if they are nested.
要反序列化整个事情:
ObjectMapper mapper = new ObjectMapper();
final MyDataObject myDataObject = mapper.readValue(json, MyDataObject.class);
这篇关于Jackson将JSON解析为Map< String,TypeA>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!