首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Gson对象键序列化HashMap

用Gson对象键序列化HashMap
EN

Stack Overflow用户
提问于 2022-03-08 13:01:24
回答 1查看 223关注 0票数 0

我正在编写一些代码来序列化我开发的一个神经网络系统。这个系统有一个“数据库”来跟踪神经网络的进化,它通过将每个基因的ID存储在一个带有HashMap的GeneKey中,这是一个记录,其中包含了基因之前的ID和我们正在存储的基因的ID。

具有某些数据的HashMap如下所示:

代码语言:javascript
运行
复制
existingNodes = {
    GeneKey[a=0, b=3] = 4,
    GeneKey[a=1, b=4] = 5
}

系统中的所有东西都可以很好地序列化,除了这个HashMap,因为Json只能将数字和字符串作为它的键,而在我的HashMap中,我使用对象作为键。是否有一种使用Gson将其序列化为json的简单方法?

编辑: HashMap是这样构造的:

代码语言:javascript
运行
复制
HashMap<GeneKey, Integer> existingNodes = new HashMap<>();

existingNodes.put(new GeneKey(0, 3), 4);
existingNodes.put(new GeneKey(1, 4), 5);

System.out.println("existingNodes = "+registry); 
//existingNodes = {
//    GeneKey[a=0, b=3] = 4,
//    GeneKey[a=1, b=4] = 5
//}

这是GeneKey类:

代码语言:javascript
运行
复制
public record GeneKey(int a, int b) {}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-08 14:19:35

如果您能够给出在使用Gson序列化后得到的JSON字符串,这将是有帮助的。

但是,如果这解决了您的问题,请检查以下代码。

使用overriden GenKey和equals方法定义hashCode类如下:

代码语言:javascript
运行
复制
public class GeneKey {
    private int a;
    private int b;
    
    public GeneKey(int a, int b) {
        this.a = a;
        this.b = b;
    }
    
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + a;
        result = prime * result + b;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        GeneKey other = (GeneKey) obj;
        if (a != other.a)
            return false;
        if (b != other.b)
            return false;
        return true;
    }

    @Override
    public String toString() {
        //return "GeneKey [a=" + a + ", b=" + b + "]";
        // Updated for deserialization using Gson
        Gson gson = new 
        GsonBuilder().serializeNulls().disableHtmlEscaping().create();
        return gson.toJson(this);
    }
}

现在,尝试使用Gson将HashMap以GenKey作为键转换为JSON字符串:

代码语言:javascript
运行
复制
HashMap<GeneKey, Integer> existingNodes = new HashMap<>();

existingNodes.put(new GeneKey(0, 3), 4);
existingNodes.put(new GeneKey(1, 4), 5);
        
Gson gson = new 
GsonBuilder().serializeNulls().disableHtmlEscaping().create();
        
System.out.println(gson.toJson(existingNodes));

这是我在控制台中收到的输出:

代码语言:javascript
运行
复制
 {"{\"a\":0,\"b\":3}":4,"{\"a\":1,\"b\":4}":5}

更新答案以添加反序列化逻辑(如果需要):

代码语言:javascript
运行
复制
//Say, we pass the serialized JSON as a payload to some REST API. We can deserialize the Key of the response as follows - 

@PostMapping("/getJson")
public Map<GeneKey, Integer> getJson(@RequestBody Map<String, Integer> response) {
        
  final Gson gson = new Gson();
  Map<GeneKey, Integer> deserializedMap = new HashMap<GeneKey, 
        Integer>();
        
  response.keySet().forEach( k -> {
  GeneKey key = gson.fromJson(k, GeneKey.class);
  deserializedMap.put(key, response.get(k));
        });

  System.out.println(deserializedMap);
  return deserializedMap;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71395518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档