【问题标题】:HashMap to POJO using GSON or Jackson使用 GSON 或 Jackson 到 POJO 的 HashMap
【发布时间】:2020-08-09 07:02:43
【问题描述】:

我的转换代码:

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

【问题讨论】:

  • 顺便说一句,成员变量应该是private。
  • 好的,谢谢,我会编辑代码

标签: java json jackson gson


【解决方案1】:

这样就可以了:

    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。但是,我不建议这样做,因为它可能最终需要更多的工作。

【讨论】:

  • 感谢您的回答,但我不想创建另一个名为实用程序的地图并将其放入第一张地图中。还有其他方法吗,如果是,请帮忙。 @aeberhart
  • @Monikaverma - 这个答案为您提供了正确的指导。而且,我不明白你为什么不想使用另一个Map。查看您的预期输出,这是最合适的。
  • 我试图解释问题本身的原因,请检查@ArvindKumarAvinash
  • @Monikaverma - 事实上,您的更新更清楚地说明了为什么这个答案是中肯的。但是,从您的更新中,仍然不清楚您为什么不想使用另一个 Map。
  • 原因很简单,我只是取了名字和手机来简化问题,地图中有数百个字段与 POJO 字段匹配,一些与 POJO 字段不匹配。不匹配的字段应进入实用程序部分。所以将隔离问题分成两个地图。 @ArvindKumarAvinash
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2013-02-03
相关资源
最近更新 更多