使用gson.getDelegateAdapter问题的Gson TypeAdapterFactory

时间:2016-10-12 21:12:22

标签: java android json gson

我遇到的问题是我的TypeAdapterFactory如何回退到默认序列化(自定义反序列化工作正常。)对于后台参考,这是用于反序列化具有obj.getTypeName的GraphQL响应,所以我必须查找类型名称并正确地反序列化。

预期行为:将对象序列化为与new Gson().fromJson相同的对象。

实际行为:将对象序列化为空/ null

public static class GsonGenericsFactory implements TypeAdapterFactory {

        private final Map<Class, Set<Class>> classes;

        public GsonGenericsFactory(Map<Class, Set<Class>> classes) {
            this.classes = classes;
        }

        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
          //returns types that implement an interface for getting typename
            Set<Class> subTypes = classes.get(type.getRawType());
            if (subTypes != null) {
                List<Class> val = new ArrayList<>(subTypes);
                final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
                final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
                return new TypeAdapter<T>() {
                    Class<T> previousClass;

                    @Override
                    public void write(JsonWriter out, T value) throws IOException {
                        delegate.write(out, value);
                    }

                    @Override
                    public T read(JsonReader in) throws IOException {
                        JsonElement tree = elementAdapter.read(in);
                        if (tree.isJsonNull()) {
                            return null;
                        }
                        for (int i = 0; i < val.size(); i++) {
                            if (isAssignable(tree, val.get(i))) {
                                previousClass = (Class<T>) val.get(i);
                                return gson.fromJson(tree, previousClass);
                            }
                        }
                        Timber.e("ERROR %S", tree.toString());
                        throw new IllegalStateException("Invalid type:" + type.toString());
                    }
                };
            }
            return null;
        }
    }

0 个答案:

没有答案