简体   繁体   English

如何使用 GSON 解析接口

[英]How to parse interfaces with GSON

I've have an interface model with nested interfaces.我有一个带有嵌套接口的接口模型。 For each interface there is also mainly 1 concrete implementation class like:对于每个接口,也主要有 1 个具体的实现类,例如:

public interface Book {

    String getTitle();
}

public class BookImpl implements Book {

    private String title;

    @Override
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Now to parse the json like:现在解析json,如:

gson.fromJson(json, Book.class);

Does not work as it does not know the implementation class.不起作用,因为它不知道实现类。

So I created a custom deserializer like:所以我创建了一个自定义解串器,如:

public class BookDeserializer implements JsonDeserializer<Book> {

    @Override
    public Book deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
        return context.deserialize(json, BookImpl.class);
    }
}

But I do this for each interface in my model.但是我对模型中的每个接口都这样做。

Is that the proper way to this?这是正确的方法吗? Creating such a simplistic deserializer?创建这样一个简单的解串器? I feel there should be an easier way.我觉得应该有更简单的方法。

Like with Jackson I would create a custom Jackson Module and register the type mapping like:与 Jackson 一样,我会创建一个自定义的 Jackson Module并注册类型映射,例如:

.addAbstractTypeMapping(Book.class, BookImpl.class)

Is this also possible with GSON? GSON也可以这样做吗?

You can use generic version of JsonDeserializer您可以使用JsonDeserializer通用版本

public static class MyDeserializer implements JsonDeserializer {
    private Class<?> implClass;

    public MyDeserializer(Class<?> c) {
        implClass = c;
    }

    @Override
    public Object deserialize(JsonElement json, Type typeOfT, 
            JsonDeserializationContext context) throws JsonParseException {
        return context.deserialize(json, implClass);
    }
}

And register it pretty much like in Jackson with one line并像在杰克逊一样用一行来注册它

builder.registerTypeAdapter(A.class, new MyDeserializer(AImpl.class));
builder.registerTypeAdapter(B.class, new MyDeserializer(BImpl.class));

Or just use lambda like或者只是使用 lambda 之类的

builder.registerTypeAdapter(G.class, (JsonDeserializer) (json, typeOfT, context)
                -> context.deserialize(json, H.class));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM