首页 > 解决方案 > 使用 GSON 或 Jackson 到 POJO 的 HashMap

问题描述

我的转换代码:

public MyEntity convert(){
            HashMap<String,String> map = new HashMap<>();
            map.put("name","akshay");
            map.put("mobile","xxxxxxx");
            map.put("soap","lux");
            map.put("noodles","maggi");
            Gson gson = new Gson();
            JsonElement jsonElement = gson.toJsonTree(map);
            MyEntity pojo = gson.fromJson(jsonElement, MyEntity.class);
            System.out.println(gson.toJson(pojo));
            return pojo;
       }

我的实体类:

public class MyEntity {
    private String name;
    private int mobile;
    private HashMap<String,String> utility;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    public HashMap<String, String> getUtility() {
        return utility;
    }

    public void setUtility(HashMap<String, String> utility) {
        this.utility = utility;
    }
}

我使用我的代码得到了什么:

{
    "name" : "akshay",
    "mobile" : 1234567890
}

但我想要像这样的输出:

{
    "name" : "akshay",
    "mobile" : 1234567890,
    "utility" : {
        "soap" : "lux",
        "noodles" : "maggi"
    }
}

GSON 没有映射 SOAP 和面条,因为 POJO 中没有对应的匹配对象。这就是我采用 hashmap 的原因。我希望 GSON 将所有不匹配的字段放入哈希图中。

效用下的键值对不固定的一件值得注意的事情取决于客户购买。我的意思是它可能是下面的其他东西。

{
    "name" : "akshay",
    "mobile" : 1234567890,
    "utility" : {
        "toothpaste" : "colgate",
        "noodles" : "maggi"
    }
}

标签: javajsonjacksongson

解决方案


这可以解决问题:

    HashMap<String, Object> map = new HashMap<>();
    map.put("name", "akshay");
    map.put("mobile", "xxxxxxx");
    HashMap<String, String> utility = new HashMap<>();
    utility.put("soap", "lux");
    utility.put("noodles", "maggi");
    map.put("utility", utility);

GSON 忽略肥皂和面条,因为它们不在正确的水平上。他们需要成为“效用”的孩子。

如果您希望以您所描述的特定方式解析“平面” JSON 结构(匹配字段以 1:1 映射,不匹配字段进入实用程序),您可以编写自定义(反)序列化程序。有关示例,请参见此问题:GSON - Custom serializer in specific case。但是,我不建议这样做,因为它可能最终需要更多的工作。


推荐阅读