如何使用Jackson将JSON对象转换为Java HashMap? [英] How to convert JSON Object to Java HashMap using Jackson?

查看:597
本文介绍了如何使用Jackson将JSON对象转换为Java HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JSON结构:

I have JSON structure like this:

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

还有像这样的豆子:

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

    //getters and setters
}

我希望将JSON中的所有键和值填充到Person类的映射中. 我不想为JSON中的每个键(例如int ageString name等)创建bean.

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.

我尝试了以下示例,它适用于如下所示的常规JSON结构:

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

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

程序是:

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

上面的程序可以正常工作,并且可以从JSON获取Hashmap中的值.但是在前面提到的Hashmap的情况下:

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"
    }
}

它不起作用,并给出NullPointerException,因为Hashmap为null.

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

有什么方法可以使用Jackson API在Person类中填充Hashmap.

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

推荐答案

在此处使用JsonAnyGetterJsonAnySetter批注.

例如:

Perosn类:

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

}

反序列化逻辑:

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

这篇关于如何使用Jackson将JSON对象转换为Java HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆