使用GSON反序列化包含JSON的对象 [英] Deserializing an object that contains JSON using GSON

查看:149
本文介绍了使用GSON反序列化包含JSON的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用gson从JSON表示反序列化POJO对象。



我希望我的一个POJO中的某个字段包含任意JSON数据。例如:

  class B {
public String stringField;
public JsonObject jsonField;
}

我希望能够调用 Gson .fromJson(json,B.class)关于以下JSON:

  {
stringField:booger,
jsonField:
{
arbitraryField1:foo
}
}

并产生 B.jsonField 包含一个带有<$ c $的JsonObject c>任意字段值 foo

然而,当我尝试这样做时, jsonField 总是一个空对象( {} )。实际上,更一般的看起来,下面总是返回一个空对象:

  new Gson()。fromJson({ foo:1},JsonObject.class)

我期望上面的代码返回一个包含字段名为 foo 值为1。



如何在将json反序列化为POJOS时使gson保留任意json数据?

解决方案

我能够通过引入一个包含JsonObject的包装器对象来解决问题,然后编写一个自定义解串器该对象只是返回原始的json。然而,似乎必须有更好的方法。



对于后人来说,反序列化器和简单的包装器对象如下所示:

  class MyJsonObjectWrapperDeserializer实现了JsonDeserializer< MyJsonObjectWrapper> {
@Override
MyJsonObjectWrapper deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context)throws JsonParseException {
return new MyJsonObjectWrapper(json.getAsJsonObject());
}
}

class MyJsonObjectWrapper {
public JsonObject json;

public MyJsonObjectWrapper(JsonObject json){
this.json = json;
}
}


I'm using gson to deserialize POJO objects from JSON representations.

I'd like one of the fields in one of my POJOs to contain arbitrary JSON data. For example:

class B {
    public String stringField;
    public JsonObject jsonField;
}

I'd like to be able to call Gson.fromJson(json, B.class) on the following JSON:

{
    "stringField": "booger",
    "jsonField" :
    {
        "arbitraryField1": "foo"
    }
}

and have the resulting B.jsonField contain a JsonObject with an arbitraryField of value foo.

However, when I attempt to do this, jsonField is always an empty object ({}). In fact, more generally, it appears that the following always returns an empty object:

new Gson().fromJson("{ foo: 1 }", JsonObject.class)

I would expect the above to return an object containing a field named foo of value 1.

How can I have gson preserve arbitrary json data when deserializing json to POJOS?

解决方案

I was able to work around the problem by introducing a wrapper object that contains a JsonObject, and then writing a custom deserializer for that object that simply returns the original json. However, it seems like there must be a better way.

For posterity, the deserializer and the trivial wrapper object look like the following:

class MyJsonObjectWrapperDeserializer implements JsonDeserializer<MyJsonObjectWrapper> {
    @Override
    public MyJsonObjectWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new MyJsonObjectWrapper(json.getAsJsonObject());
    }
}

class MyJsonObjectWrapper {
    public JsonObject json;

    public MyJsonObjectWrapper(JsonObject json) {
        this.json = json;
    }
}

这篇关于使用GSON反序列化包含JSON的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆