栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用GSON和TypeAdapter将BSON(mongoDB)读入POJO

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用GSON和TypeAdapter将BSON(mongoDB)读入POJO

我使用CustomizedTypeAdapterFactory解决了它。

基本上首先写一个定制的适配器:

public abstract class CustomizedTypeAdapterFactory<C>        implements TypeAdapterFactory{    private final Class<C> customizedClass;    public CustomizedTypeAdapterFactory(Class<C> customizedClass) {        this.customizedClass = customizedClass;    }    @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal    public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {        return type.getRawType() == customizedClass     ? (TypeAdapter<T>) customizeMyClassAdapter(gson, (TypeToken<C>) type)     : null;    }    private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type) {        final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);        return new TypeAdapter<C>() { @Override public void write(JsonWriter out, C value) throws IOException {     JsonElement tree = delegate.toJsonTree(value);     beforeWrite(value, tree);     elementAdapter.write(out, tree); } @Override public C read(JsonReader in) throws IOException {     JsonElement tree = elementAdapter.read(in);     afterRead(tree);     return delegate.fromJsonTree(tree); }        };    }        protected void beforeWrite(C source, JsonElement toSerialize) {    }        protected void afterRead(JsonElement deserialized) {    }}

然后为所有需要考虑的类创建一个子类。您必须为每个包含long的类创建一个(在这种情况下)。但是除了long值(以及任何其他bson特定值)之外,您无需序列化任何内容

public class MyTestObjectTypeAdapterFactory extends CustomizedTypeAdapterFactory<MyTestObject>{    public MyTestObjectTypeAdapterFactory()    {        super(MyTestObject.class);    }    @Override    protected void beforeWrite(MyTestObject source, JsonElement toSerialize)    {        //you could convert back the other way here, I let mongo's document parser take care of that.    }    @Override    protected void afterRead(JsonElement deserialized)    {        JsonObject timestamp = deserialized.getAsJsonObject().get("timestamp").getAsJsonObject();        deserialized.getAsJsonObject().remove("timestamp");        deserialized.getAsJsonObject().add("timestamp",timestamp.get("$numberLong"));    }}

然后生成具有以下内容的Gson:

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyTestObjectTypeAdapterFactory()).create();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371609.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号