2

我对 GSON 库有疑问

这是我的一个类的源代码

public class Response<T>
{
    public int count;
    public ArrayList<T> items;


    public Response()
    {

    }
}


public class AudioDto
{
    public long id;

    public long owner_id;

    public String artist;

    public String title;

    public long duration;

    public String url;

    public long lyrics_id;

    public long album_id;

    public long genre_id;

    @Override
    public String toString()
    {
        return "AudioDto [id=" + id + ", owner_id=" + owner_id + ", artist=" + artist + ", title=" + title + ", duration=" + duration + ", url=" + url + ", lyrics_id=" + lyrics_id + ", album_id=" + album_id + ", genre_id=" + genre_id + "]";
    }



}

和这里

        Gson gson = new Gson();

        Response<AudioDto> response = new Response<AudioDto>();
        response = gson.fromJson(responseElement, response.getClass());

问题是:

如何使 GSON 将 JSON 字符串反序列化为Response对象并将所有项目反序列化为AudioDto对象。如果我手动指定ArrayList<AudioDto>它会考虑到“项目”字段中的项目是 AudioType 类型的对象,但使用参数化类型似乎将其转换为 Object 类。

这是 JSON 字符串

{"count":166,"items":[{"id":231270625,"owner_id":205245503,"artist":"John Newman","title":"Love Me Again","duration":235,"url":"http://cs9-2v4.vk.me/p20/1ee1a056da24cb.mp3","lyrics_id":111547947,"genre_id":17},{"id":230612631,"owner_id":205245503,"artist":"Florence and The Machine","title":"No Light, No Light","duration":274,"url":"http://cs9-5v4.vk.me/p19/51a5b460796306.mp3","lyrics_id":20459437,"genre_id":18},{"id":230612324,"owner_id":205245503,"artist":"Backstreet Boys","title":"Incomplete","duration":239,"url":"http://cs9-4v4.vk.me/p13/b8dcc4cee8bf03.mp3","lyrics_id":268139,"genre_id":1}]}
4

1 回答 1

3

首先你不能使用ArrayList<T> items;,因为 Gson 试图将其转换为LinkedList.

所以 List<T>改用。

之后,您可以尝试:

GsonBuilder gsonB = new GsonBuilder();
Type collectionType = new TypeToken<Response<AudioDto>>() {}.getType();
//Response<AudioDto> response = new Response<AudioDto>();  // you don't need this row

Response<AudioDto> response = gsonB.create().fromJson(responseElement, collectionType);

//assert(response != null);

顺便说一句,Gson gson = new Gson();改用GsonBuilder gsonB = new GsonBuilder();.

那里没有什么可配置的。

关于类型

据我所知,您无法创建Type. <T>但是您可以使用Typeof<AudioDto>代替:

启动器类

....
LoadJson<AudioDto> lj = new LoadJson<AudioDto>();
Type collectionType = new TypeToken<Response<AudioDto>>() {}.getType();        
Response<AudioDto> response  = lj.load(responseElement, collectionType);  

LoadJson 类

 public class LoadJson<T> {

 Response<T> load(String responseElement, Type classType){

  Gson gson = new Gson();

    Response<T> response = gson.fromJson(responseElement, classType);

  return response;
  }
}
于 2013-09-28T10:23:37.000 回答