简体   繁体   中英

Jackson parse JSON to Map<String, TypeA>

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM