[英]Gson Generics attribute
我對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>
, ArrayList<AudioDto>
考慮到“項目”字段中的項目是ArrayList<AudioDto>
類型的對象,但參數化類型似乎將其強制轉換為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}]}
首先,您不能使用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();
。
沒什么可配置的。
關於類型
據我所知,您不能創建<T>
Type
。 但是您可以改用<AudioDto>
Type
:
發射器類
....
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.