我正在使用org.json将一个大的xml转换成json字符串。然而,对于数字0,它似乎创建了一个字符串"0",而其他数字,如5或2,则可以很好地工作,并成为实数。
xml:
<w count="2" winline="5" freespins="0" jackpot="false" start="0" payout="500" supergames="0" />java:
JSONObject json = XML.toJSONObject(xml);
String jsontext = json.toString();生成的json:
"w":[{"supergames":"0","freespins":"0","winline":5,"count":2,"start":"0","jackpot":false,"payout":500}有没有办法让0变成真正的0数字而不是字符串?
发布于 2011-02-08 21:24:39
看起来像窃听器。我查看了源代码,它看起来可能会抛出IndexOutOfBoundsException,这基本上会导致到数字的转换失败:
https://github.com/douglascrockford/JSON-java/blob/master/XML.java (第327行):
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {如果字符串以"0“开头并且长度只有1个字符,即如果字符串是"0”,则抛出。异常被捕获,转换方法基本上只是返回未转换的原始字符串("0")。
选项不多:
0.0代替0,则将XML中的“0”改为“0.0”。(发布于 2011-02-08 21:23:29
下面是将XML属性转换为JSON值的snippet of code。
我可能错了,但是没有处理值为"0“的情况。
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}https://stackoverflow.com/questions/4933322
复制相似问题