Java中的GSON嵌套哈希映射反序列化被扁平化(重复键)

huangapple go评论75阅读模式
英文:

Java GSON nested hashmap deserialization is flatmapped (duplicate key)

问题

我有一个类似这样的 JSON:

{
  "NAME": {
    "keyClass": {
      "key1": 1,
      "key2": 2
    },
    "keyClass2": {
      "key1": 6
    }
  }
}

我的 Java 代码如下:

@Expose
protected Map<String, Map<String, Integer>> data = new LinkedHashMap<>();

其中每个 Map<String,Integer> 都是一个 new LinkedHashMap<>(),然后我使用 GSON.toJson(this, File) 进行序列化,得到了上述 JSON。问题出在我尝试使用 GSON.fromJson(File, this) 进行反序列化时,它会尝试对所有内容进行映射,但某种方式它会进行扁平映射,并且不关心嵌套,因此会认为 keyClass.key1keyClass2.key1 冲突。它会抛出一个“重复的键:null”的错误。是否有一种方法可以使嵌套的 LinkedHashMap 在序列化时作为自己的对象进行处理,而在反序列化时不进行扁平映射?

英文:

I have a json like so

{
  &quot;NAME&quot;: {
    &quot;keyClass&quot;: {
      &quot;key1&quot;: 1,
      &quot;key2&quot;: 2
    },
   &quot;keyClass2&quot;: {
      &quot;key1&quot;: 6
    }
  }
}

And my java look like that

@Expose
    protected Map&lt;String, Map&lt;String, Integer&gt;&gt; data = new LinkedHashMap&lt;&gt;();

where each Map&lt;String,Integer&gt; is a new LinkedHashMap&lt;&gt;(), I then seralize that with GSON.toJson(this,File) and it give me that wonderful json, the issue arise when I try to deserialize it as GSON.fromJson(File,this) will try to map everything except that somehow it has a flatmap and doesnt care about nesting thus think keyClass.key1 and keyClass2.key1 clash. It throw a magnificient duplicate key: null . Is there some kind of object so the nested LinkedHashMap get serialized as its own and is not flatmap when deserialized?

答案1

得分: 0

抱歉,代码部分不进行翻译。以下是您要求的翻译内容:

我实际上忘记告诉一件事,我正在使用一个映射到字符串的枚举,这就是为什么在这里有两个示例,以及为什么第一个示例失败了:[链接](https://gist.github.com/hube12/b86e8257e89ed4220f03f9a527175fca)

英文:

I actually forgot to tell something, I am using an Enum which map to a string that's why, here the two examples and why it fails on the first one: https://gist.github.com/hube12/b86e8257e89ed4220f03f9a527175fca

huangapple
  • 本文由 发表于 2020年10月21日 04:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64452830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定