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

标签 java serialization gson

好的,我有一个 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/

相关文章:

java - JSON解析异常 : Expected BEGIN_ARRAY but was BEGIN_OBJECT?

java - ClassNotFoundException : edu. stanford.nlp.tagger.maxent.ExtractorNonAlphanumeric

构造函数中的 Java 成员初始化

c# - .Net Remoting 序列化问题

json - 使用 Jackson 反序列化 protected 构造函数

java - 如何通过从原始字符串中提取一些字段来生成新的 JSON 字符串?

java - 如何用Gson反序列化子类?

java - 如何找到二维数组中出现次数最多的元素?除了二维数组之外,你不能使用任何东西

java - JFreeChart 条形图自定义颜色?

c# - 如何使 Json.NET 成为默认的 Json 序列化程序