且构网

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

使用 Gson 的自定义 JSON 反序列化器

更新时间:2022-05-28 09:38:12

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

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