Reputation: 329
I have the following JSON:
{
"data": {
"1": {
"id":"1",
"name":"test1"
},
"2": {
"id":"2",
"name":"test2"
}
}
}
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.
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:
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
Upvotes: 0
Views: 2938
Reputation: 19231
The following should work out for you.
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;
}
}
The @JsonCreator
is used for describing how to create your objects together with the name of the properties @JsonProperty
. Even if they are nested.
To deserialize the whole thing:
ObjectMapper mapper = new ObjectMapper();
final MyDataObject myDataObject = mapper.readValue(json, MyDataObject.class);
Upvotes: 1