英文:
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.key1
和 keyClass2.key1
冲突。它会抛出一个“重复的键:null”的错误。是否有一种方法可以使嵌套的 LinkedHashMap
在序列化时作为自己的对象进行处理,而在反序列化时不进行扁平映射?
英文:
I have a json like so
{
"NAME": {
"keyClass": {
"key1": 1,
"key2": 2
},
"keyClass2": {
"key1": 6
}
}
}
And my java look like that
@Expose
protected Map<String, Map<String, Integer>> data = new LinkedHashMap<>();
where each Map<String,Integer>
is a new LinkedHashMap<>()
, 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论