GSON: serialize/deserialize object of class, that have registered type hierarchy adapter, using ReflectiveTypeAdapterFactory.Adapter

三世轮回 提交于 2019-12-19 11:57:09

问题


To be clear, let introduse some model:

interface A {
    boolean isSomeCase();
}

class AAdapter implements JsonSerializer<A> {
    public JsonElement serialize(A src, Type typeOfSrc, JsonSerializationContext context) {
        if (src.isSomeCase()) {
            /* some logic */
            return result;
        } else {
            JsonObject json = new JsonObject();
            JsonElement valueJson = <???>; // TODO serialize src like POJO
            json.add(src.getClass().getSimpleName(), valueJson);
            return json;
        } 
    }
}

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(A.class. new AAdapter())
        .create();

How it is possible to serealize some instance of A, which isSomeCase() = false, like any other object, that is serialized by ReflectiveTypeAdapterFactory.Adapter.


回答1:


You can write a custom TypeAdapterFactory and handle incoming object's isSomeCase() result in its TypeAdapter's write() method and apply your logic there:

public class ATypeAdapterFactory implements TypeAdapterFactory {

    public TypeAdapter<A> create(Gson gson, TypeToken type) {
        if (!A.class.isAssignableFrom(type.getRawType())) {
            // Check if incoming raw type is an instance of A interface
            return null;
        } 

        final TypeAdapter<A> delegate = gson.getDelegateAdapter(this, type);

        return new TypeAdapter<A>() {

            @Override
            public void write(JsonWriter out, A value) throws IOException {
                if(value.isSomeCase()) {
                    // your custom logic here
                    out.beginObject();
                    out.name("x").value(0);
                    out.endObject();
                } else {
                    // default serialization here
                    delegate.write(out, value);
                }
            }

            @Override
            public A read(JsonReader in) throws IOException {
                return delegate.read(in);
            }
        };
    }
}

Test:

final GsonBuilder gsonBuilder = new GsonBuilder();
// Register custom type adapter factory
gsonBuilder.registerTypeAdapterFactory(new ATypeAdapterFactory());
final Gson gson = gsonBuilder.create();

A aSomeCaseTrue = new AImpl(true);
System.out.print("aSomeCaseTrue:" + gson.toJson(aSomeCaseTrue));
// writes; aSomeCaseTrue:{"x":0}


A aSomeCaseFalse = new AImpl(false);
System.out.print("aSomeCaseFalse:" + gson.toJson(aSomeCaseFalse););
// writes; aSomeCaseFalse:{"someCase":false}

Extras:

1) Your interface:

interface A {
    boolean isSomeCase();
}

2) A sample class which implements your sample interface:

class AImpl implements A {
    boolean someCase;

    public AImpl(boolean value) {
        this.someCase = value;
    }

    @Override
    public boolean isSomeCase() {
        return someCase;
    }
}


来源:https://stackoverflow.com/questions/26592904/gson-serialize-deserialize-object-of-class-that-have-registered-type-hierarchy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!