使用 Gson 的自定义 JSON 反序列化器 [英] Custom JSON deserializer using Gson

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

问题描述

我在使用 Gson 解析 JSON 响应时遇到问题.

I have a problem with parsing a JSON response using Gson.

JSON 字符串:

response: [
  2, {
    owner_id: 23972237,
    album_id: 25487692,
    title: 'album not new'
  }, {
    owner_id: 23972237,
    album_id: 25486631,
    title: 'фыв'
  }
]

我有这两个类:

public class VkAudioAlbumsResponse {
    public ArrayList<VkAudioAlbum> response;
    public VkError error;
}

public class VkAudioAlbum {
    public int owner_id;
    public int album_id;
    public String title;
}

但是我在使用 Gson 解析这个时有一个异常.我知道这是因为响应数组的第一个元素不是对象,而是整数.

But I have an Exception when parse this using Gson. I know this is because response array first element is not an object, but integer.

那么问题是,我能以某种方式解决它吗?

So the question is, can I solve it somehow?

推荐答案

你必须写一个 自定义反序列化器.我会做这样的事情:

You have to write a custom deserializer. I'd do something like this:

首先,您需要包含一个新类,比您已有的 2 个类更进一步:

First you need to include a new class, further than the 2 you already have:

public class Response {
    public VkAudioAlbumsResponse response;
}

然后你需要一个自定义的解串器,类似于这个:

And then you need a custom deserializer, something similar to this:

private class VkAudioAlbumsResponseDeserializer 
    implements JsonDeserializer<VkAudioAlbumsResponse> {

  @Override
  public VkAudioAlbumsResponse deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    JsonArray jArray = (JsonArray) json;

    int firstInteger = jArray.get(0); //ignore the 1st int

    VkAudioAlbumsResponse vkAudioAlbumsResponse = new VkAudioAlbumsResponse();

    for (int i=1; i<jArray.size(); i++) {
      JsonObject jObject = (JsonObject) jArray.get(i);
      //assuming you have the suitable constructor...
      VkAudioAlbum album = new VkAudioAlbum(jObject.get("owner_id").getAsInt(), 
                                            jObject.get("album_id").getAsInt(), 
                                            jObject.get("title").getAsString());
      vkAudioAlbumsResponse.getResponse().add(album);
    }

    return vkAudioAlbumsResponse;
  }  
}

然后你必须像这样反序列化你的 JSON:

Then you have to deserialize your JSON like:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(VkAudioAlbumsResponse.class, new VkAudioAlbumsResponseDeserializer());
Gson gson = gsonBuilder.create();
Response response = gson.fromJson(jsonString, Response.class);

使用这种方法,当 Gson 尝试将 JSON 反序列化为 Response 类时,它发现该类中有一个与 JSON 中的名称匹配的属性 response响应,所以它继续解析.

With this approach, when Gson tries to deserialize the JSON into Response class, it finds that there is an attribute response in that class that matches the name in the JSON response, so it continues parsing.

然后它意识到这个属性是VkAudioAlbumsResponse类型,所以它使用你创建的自定义反序列化器来解析它,它处理JSON响应的剩余部分并返回一个VkAudioAlbumsResponse.

Then it realises that this attribute is of type VkAudioAlbumsResponse, so it uses the custom deserializer you have created to parse it, which process the remaining portion of the JSON response and returns an object of VkAudioAlbumsResponse.

注意:解串器中的代码非常简单,所以我想你理解它应该没有问题...更多信息请参见 Gson API Javadoc

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

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