我正在使用GSON來解析Java中的json。當我想從一個JSON字符串的整數列表,我的代碼看起來是這樣的:找出GSON的TypeToken是否包含列表?
Type type = new TypeToken<List<Integer>>(){}.getType();
List<Integer> result = null;
try {
result = new Gson().fromJson(jsonStringGoesHere, type);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
如果jsonStringGoesHere
是一個空字符串或NULL,result
也爲空。
但是,如果Collection的值等於null,這被認爲是不好的做法,所以我寧願在這種情況下有一個空的List而不是null。
所以基本上這就是我想現在要做的:如果result
是空的,我要檢查,如果type
是List
(或List
亞型)。如果爲true,我會使結果成爲一個空ArrayList。我如何檢查type
是否包含List
或List
的子類型?
我的嘗試是檢查if(type instanceof Collection)
- 但返回false。
我的下一個嘗試是採取type.getTypeName()
它返回字符串java.util.List<java.lang.Integer>
,並試圖從創建一個對象:
Class c = Class.forName(type.getTypeName());
Object o = c.newInstance();
if(o instanceof List){
System.out.println("it's working!");
}
但這拋出。
任何想法如何使這項工作?
將List更改爲ArrayList中的Type Type = new TypeToken>(){}。getType();'。檢查http://stackoverflow.com/questions/4818228/how-to-instantiate-a-java-util-arraylist-with-generic-class-using-reflection –
Ibrahim
@Ibrahim這樣做,'結果'仍爲空,'' instanceof'仍然返回false,並且創建newInstance()仍會拋出java.lang.ClassNotFoundException:java.util.ArrayList。 –
user2015253