本文介绍了GSON无法正确序列化扩展HashMap的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public static class A
{
    public A() {}
    private List<B> bs = new ArrayList<B>();
    public List<B> getBs() {
        return bs;
    }
    public void setBs(List<B> bs) {
        this.bs = bs;
    }
}

public static class B
{
    B(String foo){this.foo=foo;}
    private String foo;
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

public static void main(String[] args) throws Exception {
    Gson gson = new Gson();
    A a = new A();
    a.getBs().add(new B("bar"));
    System.out.println(gson.toJson(a));
}

并且按预期,输出为:

{"bs":[{"foo":"bar"}]}

但是,如果我将A作为HashMap的子类:

However, if I make A a subclass of HashMap:

public static class A extends HashMap

我得到一个空集,返回:{}

I get an empty set returned: {}

我什至尝试过:

System.out.println(gson.toJson(a, new TypeToken<A>(){}.getType()));

和:

System.out.println(gson.toJson(a, new TypeToken<HashMap>(){}.getType()));

有人可以告诉我是否/如何使用GSON序列化此HashMap子类?

Can someone tell me whether/how I can serialise this HashMap subclass using GSON?

推荐答案

Gson可与(默认和自定义) TypeAdapterFactory 实例以及它们创建以进行序列化/的 TypeAdapter 对象一起使用反序列化您的对象.

Gson works with (default and custom) TypeAdapterFactory instances and the TypeAdapter objects they create to serialize/deserialize your objects.

它将遍历已注册的 TypeAdapterFactory 对象的列表,并选择第一个可以为要提供的对象类型创建合适的 TypeAdapter 的对象.这些 TypeAdapterFactory 对象之一是类型 MapTypeAdapterFactory 之一,它创建一个 TypeAdapter (类型为 MapTypeAdapterFactory $ Adapter )根据 java.util.Map 接口(键/值)进行序列化/反序列化的代码.它对您的自定义子类型的字段不起作用.

It goes through the list of registered TypeAdapterFactory objects and picks the first one that can create an appropriate TypeAdapter for the type of the object your are providing. One of these TypeAdapterFactory objects, is one of type MapTypeAdapterFactory which creates a TypeAdapter (of type MapTypeAdapterFactory$Adapter) that serializes/deserializes based on the java.util.Map interface (keys/values). It does nothing about your custom sub type's fields.

如果您希望Gson将您的类型序列化为 Map 和自定义类型,则需要直接注册自定义 TypeAdapter 或自定义创建 TypeAdapter 对象的TypeAdapterFactory .

If you want Gson to serialize your type as both a Map and a custom type, you will need to register either a custom TypeAdapter directly or a custom TypeAdapterFactory that creates TypeAdapter objects.

这篇关于GSON无法正确序列化扩展HashMap的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:47