【问题标题】:Two hashmap to entity class [closed]实体类的两个哈希图[关闭]
【发布时间】:2020-08-08 08:00:36
【问题描述】:

我有两个HashMap 我想使用 GSON 反序列化为实体类。

void convert(){
    HashMap<String,String> map1 = new HashMap<>();
    map1.put("key1","value1");
    map1.put("key2","value2");
    HashMap<String,String> map2 = new HashMap<>();
    map2.put("key3","value3");
    map2.put("key4","value4");
    Gson gson = new Gson();
    String service = gson.toJson(map2);
    map1.put("service", service);
    String json = gson.toJson(map1);
    MyModel myModel = gson.fromJson(json, MyModel.class);
    System.out.println(gson.toJson(myModel));
}

我的实体类

 public class MyModel {
    String key1;
    String key2;
    String service;
    public String getKey1() {
        return key1;
    }
    public void setKey1(String key1) {
        this.key1 = key1;
    }
    public String getKey2() {
        return key2;
    }
    public void setKey2(String key2) {
        this.key2 = key2;
    }
    public String getService() {
        return service;
    }
    public void setService(String service) {
        this.service = service;
    }
}

有没有什么有效的方法来做到这一点。

【问题讨论】:

  • 如果你想从地图创建 json,为什么要使用MyModel
  • 你想清楚你的问题,你的输入和输出是什么。意味着您来自 json 的 MyModel ?或映射到 json ?
  • service 可以是另一个 POJO 类。甚至您也可以将其声明为Map。这完全取决于您的要求。
  • 使服务成为哈希图,它会起作用
  • I want involve entity class 为什么要涉及实体类?你想要映射到 json 和映射到实体类吗?

标签: java json jackson gson


【解决方案1】:

可以直接将HashMap转成json

HashMap<String,Object> map1 = new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
HashMap<String,String> map2 = new HashMap<>();
map2.put("key3","value3");
map2.put("key4","value4");
 
map1.put("service", map2);
String result = gson.toJson(map1);

如果你想将 json 转换为实体类

MyModel myModel = gson.fromJson(result, MyModel.class);

并使用Map&lt;String,String&gt; 作为服务字段

public class MyModel {
    String key1;
    String key2;
    Map<String,String> service;
    ...
}

【讨论】:

  • 注意:OP在问题中更新他的代码
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 2018-04-24
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2010-09-15
  • 2013-06-24
  • 2019-12-20
相关资源
最近更新 更多