使用null int的Gson反序列化似乎无法工作
当我在网络上下载数据时,有时它可以工作,有时它不会。 而我的问题是,在一个int
: 运行:“”使用null int的Gson反序列化似乎无法工作
运行时是一个int,当我使用GSON它可能会导致此问题:
01-07 21:22:57.602: E/AndroidRuntime(2726): Caused by: java.lang.NumberFormatException: Invalid int: ""
,我想一些if语句,但它不起作用。
public int getRuntime() {
if(Integer.valueOf(runtime)==null){
return 0;
}else{
return runtime;
}
}
甚至
public int getRuntime() {
if(Integer.valueOf(runtime).equals(null)){
return 0;
}else{
return runtime;
}
}
但没有任何工程。
Integer.valueOf()需要一个表示整数的String。用空字符串调用它将lead to an exception。你需要分析它作为一个整数之前测试的字符串:
int runtime;
if ("".equals(string)) {
runtime = 0;
}
else {
runtime = Integer.parseInt(string);
}
,或者,如果你总是希望这样的运行时间为0,如果该字符串不是有效的整数,然后捕获异常:
try {
runtime = Integer.parseInt(string);
}
catch (NumberFormatException e) {
runtime = 0;
}
现在,它是为你解析字符串的gson,并且这个字符串并不总是一个整数,那么runtime
字段不应该是int,而应该是一个String。你应该自己解析它,如上所示。
鉴于您的问题,在尝试使用gson和android做任何事情之前,您应该了解Java语言的基础知识。您似乎并不了解Java中的类型系统以及有哪些例外情况。阅读http://docs.oracle.com/javase/tutorial/java/nutsandbolts/
您需要首先检查runtime
,例如, if(runtime.isEmpty())
或更好 - 使用apache commons lang - if(StringUtils.isBlank(runtime))
或捕获抛出的NumberFormatException
。
它看起来像你有什么不明白的例外是,或如何处理它们:
http://docs.oracle.com/javase/tutorial/essential/exceptions
public int getRuntime() {
int i = 0;
try {
i = Integer.valueOf(runtime);
} catch (NumberFormatException e) {
System.out.println("runtime wasn't an int, returning 0");
}
return i;
}
提示:无论运行时,它不是任何可以被转换成int 。从您发布的内容看,它看起来像一个空字符串
将运行时作为字符串处理,将其声明为要反序列化的类中的字符串。
然后使用这样的GSON将处理空值正确
Gson gson = new GsonBuilder().serializeNulls().create();
序列化时,通常如果值是null,则它将只是没有放任何东西在JSON序列化这工作也。
它看起来像你不明白什么是异常或如何处理它们:http://docs.oracle.com/javase/tutorial/essential/exceptions/ 提示:无论“运行时”是什么,它不是任何可以转换为“int”的东西。从你发布的内容看,它看起来像一个空的'String' – 2012-01-07 20:31:32
,但是当数据运行时它是一个数字而不是一个字符串,这很奇怪。 – Tsunaze 2012-01-07 20:34:52
@Tsunaze JSON是_always_字符串,数字只是文本编码。很像你在这里看到的数字1234(在我的评论:))不是一个数字,而是一个可以被解析成数字的字符串。 – Thomas 2012-01-07 20:37:25