1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00

stringToValue

This commit is contained in:
Douglas Crockford 2013-11-14 11:18:16 -08:00
parent 34f327e6d0
commit 4d86b05d3c

View file

@ -31,7 +31,7 @@ import java.util.Iterator;
* This provides static methods to convert an XML text into a JSONObject, * This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text. * and to covert a JSONObject into an XML text.
* @author JSON.org * @author JSON.org
* @version 2012-10-26 * @version 2013-11-12
*/ */
public class XML { public class XML {
@ -301,9 +301,6 @@ public class XML {
* @return A simple JSON value. * @return A simple JSON value.
*/ */
public static Object stringToValue(String string) { public static Object stringToValue(String string) {
if ("".equals(string)) {
return string;
}
if ("true".equalsIgnoreCase(string)) { if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE; return Boolean.TRUE;
} }
@ -313,36 +310,26 @@ public class XML {
if ("null".equalsIgnoreCase(string)) { if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL; return JSONObject.NULL;
} }
if ("0".equals(string)) {
return new Integer(0);
}
// If it might be a number, try converting it. If that doesn't work, // If it might be a number, try converting it, first as a Long, and then as a
// return the string. // Double. If that doesn't work, return the string.
try { try {
char initial = string.charAt(0); char initial = string.charAt(0);
boolean negative = false; if (initial == '-' || (initial >= '0' && initial <= '9')) {
if (initial == '-') { Long value = new Long(string);
initial = string.charAt(1); if (value.toString().equals(string)) {
negative = true; return value;
}
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) { } catch (Exception ignore) {
try {
Double value = new Double(string);
if (value.toString().equals(string)) {
return value;
}
} catch (Exception ignoreAlso) {
}
} }
return string; return string;
} }