How to convert JSON Object to Java HashMap using Jackson?

陌路散爱 提交于 2019-12-23 04:59:16

问题


I have JSON structure like this:

{   
    "person": 
    {
        "name": "snoop",
        "age": "22",
        "sex": "male"
    }
}

And beans like this:

public class Person {
    HashMap<String,String> map;

    //getters and setters
}

I want all key and value from JSON to be filled inside map from Person class. I do not want to create bean for each key from JSON like int age, String name etc.

I have tried following example and it worked for normal JSON structure like below:

{
    "type": "Extends",
    "target": "application",
    "ret": "true"
}

and program is:

String jsonString = "{\"type\": \"Extends\", \"target\": \"application\", \"ret\":\"true\" }";

ObjectMapper mapper = new ObjectMapper();
try {
    Map<String, Object> carMap = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
    });

    for (Entry<String, Object> entry : carMap.entrySet()) {
        System.out.println("key=" + entry.getKey() + " and value=" + entry.getValue());
    }

} catch (Exception e) {
    e.printStackTrace();
}

Above program works fine and gets values in Hashmap from JSON. But in case of previously mentioned Hashmap:

{   
    "person": 
    {
        "name": "snoop",
        "age": "22",
        "sex": "male"
    }
}

it doesn't work and gives NullPointerException as Hashmap is null.

Is there any way we can use Jackson API to populate Hashmap within Person class.


回答1:


use JsonAnyGetter and JsonAnySetter annotation here.

E.g:

Perosn class:

@JsonRootName("person")
class Person {
    HashMap<String, String> map = new HashMap<>();

    @JsonAnyGetter
    public Map<String, String> getMap() {
        return map;
    }

    @JsonAnySetter
    public void setMap(String name, String value) {
        map.put(name, value);
    }

}

Deserialization logic:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Person person = mapper.readValue(jsonString, Person.class);


来源:https://stackoverflow.com/questions/43246240/how-to-convert-json-object-to-java-hashmap-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!