【问题标题】:Serialize object map with gson - object is incomplete使用 gson 序列化对象映射 - 对象不完整
【发布时间】:2019-06-01 07:43:48
【问题描述】:

我想序列化一个对象 Bar,它包含原始类型和一个 HashMap。

public class Bar{
 int simpleValue;
 HashMap<Foo,Integer> map;
...
}

public class Foo{
 ...
}

我使用 Gson 创建一个 Json-String:

Gson gson = new Gson();
String json = gson.toJson(barObject);

这会产生以下字符串:

{"simpleValue":9,"map":{"com.blabla.Foo@2d9b7da":120,...}}

为什么只有对象名称的字符串表示?

我做错了什么?

gson.toJson(fooObject) 打印出 Foo 的正确属性...

【问题讨论】:

    标签: java serialization gson


    【解决方案1】:

    您的代码正在打印出对象名称的字符串表示形式,因为 Bar 类有一个 Map 对象,其键是其 toString() 未被覆盖的类。
    gson 使用toString() 实现生成 json 密钥。
    由于您还没有实现它,它正在回退到默认的Object.toString() 来生成密钥。因此输出。

    以下是演示行为的来源,

    public class Bar {
        Map<Foo, Integer> map;
        public static void main(String[] args) {
            Gson g = new Gson();
            TracingAspect t = new Bar();
            t.map = new HashMap<>();
            t.map.put(new Foo("ff"), 5);
            String j = g.toJson(t);
            System.out.println(j);
        }
    
    }
    class Foo {
        String a;
        public Foo (String a) {this.a=a;}
        @Override
        public String toString () {
            return a;
        }
    }
    

    下面的输出是,

    {"map":{"ff":5}}
    

    【讨论】:

    • 谢谢!另外:我刚刚在 gson 中找到了“enableComplexMapKeySerialization()”设置,这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多