我正在使用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