使用Gson

时间:2018-01-18 06:39:36

标签: java json gson guava java-6

这是我想要序列化的POJO:

public class Bar {
    private final Foo foo;

    private final Iterable<String> list;

    private final Iterable<Map<String, String>> listOfMaps;
}

以下是我如何称呼它

Bar bar = new Bar();
Foo foo = new Foo();
foo.field1 = "val1";
foo.field2 = "val2";
bar.foo = foo;
bar.list = ImmutableList.<String>of("fooList");
bar.listOfMaps = ImmutableList.<Map<String,String>>of(
                    ImmutableMap.<String,String>of("key", "val")
                );
new Gson().toJson(bar);

结果如下

{"foo":{"field1":"val1","field2":"val2"},"list":{},"listOfMaps":{}}

正如您所看到的,POJO序列化很好,但是可迭代(番石榴集合的实例)没有正确地序列化为JSON。当我自己序列化字段时,它们显示正常,但当它们是Bar

字段时,它不能正确序列化

示例:

new Gson().toJson(bar.list);

["fooList"]

1 个答案:

答案 0 :(得分:0)

对于Gson来说,这看起来是一个老问题,这就是它最初的设计方式。 我有一些假设,为什么它可能是这样设计的,但我认为我的假设很弱(Iterable只是太基类型而不能默认获得特定的实现?)它可能与Collection和{ {1}}?;如果List返回无限迭代器怎么办?)。 您可以通过此拉取请求追踪Iterable支持问题:https://github.com/google/gson/pull/854

首先,为什么Gson对你提到的两种情况都有不同的表现(Iterable.toJson(bar))。 对于第一种情况,Gson扫描您的.toJson(bar.list)对象,它使用反射直接从字段中检索类型信息,这是它获取bar的位置。 对于第二种情况,Gson没有声明类型信息因此它只需要使用Iterable丢失类型参数化的实际类(不是类型!)(字符串适合此测试转换完美), .getClass()在这种情况下,Gson支持开箱即用。 请注意,后者也可以使用Collection显示给定对象类型(不是类!)明确地再现。

但是,您可以自己添加gson.toJson(..., new TypeToken<Iterable<String>>() {}.getType(), System.out)支持,但我不确定以下实施是否需要更多工作:

Iterable
final class IterableMyTypeAdapterFactory
        implements TypeAdapterFactory {

    private static final TypeAdapterFactory iterableTypeAdapterFactory = new IterableMyTypeAdapterFactory();

    private IterableMyTypeAdapterFactory() {
    }

    // It's an effective singleton but we do not reveal it
    static TypeAdapterFactory getIterableMyTypeAdapterFactory() {
        return iterableTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        // Must be an iterable, subclasses should be picked up by built-in type adapters
        if ( !Iterable.class.isAssignableFrom(typeToken.getRawType()) || Collection.class.isAssignableFrom(typeToken.getRawType()) ) {
            // Tell Gson to pick up on its own
            return null;
        }
        // Extract the element type. If it's raw, we assume java.lang.Object is in the play
        final Type elementType = getTypeParameter0(typeToken.getType());
        // Get the element type adapter
        final TypeAdapter<?> elementTypeAdapter = gson.getDelegateAdapter(this, TypeToken.get(elementType));
        // And get rid of wildcards
        @SuppressWarnings("unchecked")
        final TypeAdapter<Object> castElementTypeAdapter = (TypeAdapter<Object>) elementTypeAdapter;
        // Instantiating a new iterable type adapter
        final TypeAdapter<Iterable<Object>> iterableTypeAdapter = IterableTypeAdapter.get(castElementTypeAdapter);
        // Cast it cheating javac
        @SuppressWarnings("unchecked")
        final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) iterableTypeAdapter;
        return castTypeAdapter;
    }

    private static Type getTypeParameter0(final Type type) {
        if ( !(type instanceof ParameterizedType) ) {
            return Object.class;
        }
        final ParameterizedType parameterizedType = (ParameterizedType) type;
        return parameterizedType.getActualTypeArguments()[0];
    }

    private static final class IterableTypeAdapter<E>
            extends TypeAdapter<Iterable<E>> {

        private final TypeAdapter<E> elementTypeAdapter;

        private IterableTypeAdapter(final TypeAdapter<E> elementTypeAdapter) {
            this.elementTypeAdapter = elementTypeAdapter;
        }

        private static <E> TypeAdapter<Iterable<E>> get(final TypeAdapter<E> elementTypeAdapter) {
            return new IterableTypeAdapter<>(elementTypeAdapter)
                    .nullSafe(); // We don't need to handle nulls ourselves anymore
        }

        @Override
        @SuppressWarnings("resource")
        public void write(final JsonWriter jsonWriter, final Iterable<E> elements)
                throws IOException {
            // Emit [
            jsonWriter.beginArray();
            for ( final E e : elements ) {
                // Write each element to the downstream writer
                elementTypeAdapter.write(jsonWriter, e);
            }
            // Emit ]
            jsonWriter.endArray();
        }

        @Override
        @SuppressWarnings("resource")
        public Iterable<E> read(final JsonReader jsonReader)
                throws IOException {
            jsonReader.beginArray(); // Expect [
            final Collection<E> elements = new ArrayList<>(); // This is probably why there is Iterable support by default
            while ( jsonReader.hasNext() ) {
                final E e = elementTypeAdapter.read(jsonReader); // Read each element
                elements.add(e);
            }
            jsonReader.endArray(); // Expect ]
            return elements;
        }

    }

}

之前的输出:

private static final class Pack {

    Iterable<String> iterable;
    Collection<String> collection;
    List<String> list;
    Map<String, String> map;

}

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(getIterableMyTypeAdapterFactory())
        .create();

public static void main(final String... args) {
    final List<String> fooBar = ImmutableList.of("foo", "bar");
    final Pack pack = new Pack();
    pack.iterable = fooBar;
    pack.collection = fooBar;
    pack.list = fooBar;
    pack.map = ImmutableMap.of("foo", "bar");
    gson.toJson(pack, System.out);
}

输出之后:

{"iterable":{},"collection":["foo","bar"],"list":["foo","bar"],"map":{"foo":"bar"}}