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

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


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解析这个时我有一个异常。我知道这是因为响应数组的第一个元素不是对象,而是整数。


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


拉丁的传说
浏览 352回答 1
1回答

慕少森

您必须编写一个自定义反序列化器。我会做这样的事情:首先,您需要包括一个新的类,而不是已有的两个类:public class Response {&nbsp; &nbsp; public VkAudioAlbumsResponse response;}然后,您需要一个自定义解串器,类似于以下内容:private class VkAudioAlbumsResponseDeserializer&nbsp;&nbsp; &nbsp; implements JsonDeserializer<VkAudioAlbumsResponse> {&nbsp; @Override&nbsp; public VkAudioAlbumsResponse deserialize(JsonElement json, Type type,&nbsp; &nbsp; &nbsp; &nbsp; JsonDeserializationContext context) throws JsonParseException {&nbsp; &nbsp; JsonArray jArray = (JsonArray) json;&nbsp; &nbsp; int firstInteger = jArray.get(0); //ignore the 1st int&nbsp; &nbsp; VkAudioAlbumsResponse vkAudioAlbumsResponse = new VkAudioAlbumsResponse();&nbsp; &nbsp; for (int i=1; i<jArray.size(); i++) {&nbsp; &nbsp; &nbsp; JsonObject jObject = (JsonObject) jArray.get(i);&nbsp; &nbsp; &nbsp; //assuming you have the suitable constructor...&nbsp; &nbsp; &nbsp; VkAudioAlbum album = new VkAudioAlbum(jObject.get("owner_id").getAsInt(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jObject.get("album_id").getAsInt(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jObject.get("title").getAsString());&nbsp; &nbsp; &nbsp; vkAudioAlbumsResponse.getResponse().add(album);&nbsp; &nbsp; }&nbsp; &nbsp; return vkAudioAlbumsResponse;&nbsp; }&nbsp;&nbsp;}然后,您必须像这样反序列化JSON:GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(VkAudioAlbumsResponse.class, new VkAudioAlbumsResponseDeserializer());Gson gson = gsonBuilder.create();Response response = gson.fromJson(jsonString, Response.class);使用这种方法,当Gson尝试将JSON反序列化为Response类时,它将发现该类中存在一个response与JSON响应中的名称匹配的属性,因此它将继续进行解析。然后,它意识到此属性是类型的VkAudioAlbumsResponse,因此它将使用您创建的自定义反序列化器对其进行解析,该反序列化器将处理JSON响应的其余部分并返回对象VkAudioAlbumsResponse。注意:反序列化器中的代码非常简单,因此我想您将毫无疑问地了解它...有关更多信息,请参见Gson API Javadoc
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java