gpt4 book ai didi

java - Gson:更改映射键的序列化方式

转载 作者:行者123 更新时间:2023-11-30 03:04:32 26 4
gpt4 key购买 nike

好的,我有一个 Map<Vector3i,String>我想保存,问题是,我只需要 x,z 值,所以结果应该如下所示:

{
"1,2": "test"
"13,5": "test"
"9,4": "test"
}

这是我的JsonSerializer<Vector3i> :

public class Vector3iAdapter implements JsonSerializer<Vector3i> {
@Override
public JsonElement serialize(Vector3i src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getX()+","+ src.getZ());
}
}

但这就是输出的样子:

{
"(1, 0, 2)": "test"
"(13, 0, 5)": "test"
"(9, 0, 4)": "test"
}

自从序列化 Vector3i它不能用作 Map 中的键我问,它按预期工作,为什么它的行为不同以及我将如何解决这个问题。

最佳答案

我认为在 Gson.Builder 上调用 enableComplexMapKeySerialization() 应该可以解决问题。来自 the Gson documentation:

Enabling this feature will only change the serialized form if the map key is a complex type (i.e. non-primitive) in its serialized JSON form. The default implementation of map serialization uses toString() on the key; however, when this is called then one of the following cases apply...

此外,如果您计划稍后也反序列化 JSON,您应该阅读以下答案:https://stackoverflow.com/a/14677564/763935

关于java - Gson:更改映射键的序列化方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com