且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取嵌套的JSON对象使用改造GSON

更新时间:2023-01-16 21:29:46

您可以编写一个自定义解串器,返回嵌入对象。

You would write a custom deserializer that returns the embedded object.

比方说,你的JSON是:

Let's say your JSON is:

{
    "status":"OK",
    "reason":"some reason",
    "content" : 
    {
        "foo": 123,
        "bar": "some value"
    }
}

您会再有一个内容 POJO:

You'd then have a Content POJO:

class Content
{
    public int foo;
    public String bar;
}

然后你写一个解串器:

Then you write a deserializer:

class MyDeserializer implements JsonDeserializer<Content>
{
    @Override
    public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException
    {
        // Get the "content" element from the parsed JSON
        JsonElement content = je.getAsJsonObject().get("content");

        // Deserialize it. You use a new instance of Gson to avoid infinite recursion
        // to this deserializer
        return new Gson().fromJson(content, Content.class);

    }
}

现在,如果你建立一个 GSON GsonBuilder 并注册解串器:

Now if you construct a Gson with GsonBuilder and register the deserializer:

Gson gson = 
    new GsonBuilder()
        .registerTypeAdapter(Content.class, new MyDeserializer())
        .create();

您可以直接反序列化的JSON到你的内容

You can deserialize your JSON straight to your Content:

Content c = gson.fromJson(myJson, Content.class);

修改,从添加注释:

如果您有不同类型的消息,但他们都有内容区域,就可以使解串器通用这样做:

If you have different types of messages but they all have the "content" field, you can make the Deserializer generic by doing:

class MyDeserializer<T> implements JsonDeserializer<T>
{
    @Override
    public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException
    {
        // Get the "content" element from the parsed JSON
        JsonElement content = je.getAsJsonObject().get("content");

        // Deserialize it. You use a new instance of Gson to avoid infinite recursion
        // to this deserializer
        return new Gson().fromJson(content, type);

    }
}

您只需要注册一个实例,为每个类型的:

You just have to register an instance for each of your types:

Gson gson = 
    new GsonBuilder()
        .registerTypeAdapter(Content.class, new MyDeserializer<Content>())
        .registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>())
        .create();

当你调用 .fromJson()类型带入解串器,所以它应该再适用于所有的类型。

When you call .fromJson() the type is carried into the deserializer, so it should then work for all your types.