@@ -31,7 +31,7 @@ of this software and associated documentation files (the "Software"), to deal
3131 * This provides static methods to convert an XML text into a JSONObject,
3232 * and to covert a JSONObject into an XML text.
3333 * @author JSON.org
34- * @version 2010-04-08
34+ * @version 2010-12-23
3535 */
3636public class XML {
3737
@@ -226,7 +226,7 @@ private static boolean parse(XMLTokener x, JSONObject context,
226226 if (!(t instanceof String )) {
227227 throw x .syntaxError ("Missing value" );
228228 }
229- o .accumulate (s , JSONObject .stringToValue ((String )t ));
229+ o .accumulate (s , XML .stringToValue ((String )t ));
230230 t = null ;
231231 } else {
232232 o .accumulate (s , "" );
@@ -258,7 +258,7 @@ private static boolean parse(XMLTokener x, JSONObject context,
258258 } else if (t instanceof String ) {
259259 s = (String )t ;
260260 if (s .length () > 0 ) {
261- o .accumulate ("content" , JSONObject .stringToValue (s ));
261+ o .accumulate ("content" , XML .stringToValue (s ));
262262 }
263263
264264// Nested element
@@ -285,6 +285,60 @@ private static boolean parse(XMLTokener x, JSONObject context,
285285 }
286286
287287
288+ /**
289+ * Try to convert a string into a number, boolean, or null. If the string
290+ * can't be converted, return the string. This is much less ambitious than
291+ * JSONObject.stringToValue, especially because it does not attempt to
292+ * convert plus forms, octal forms, hex forms, or E forms lacking decimal
293+ * points.
294+ * @param string A String.
295+ * @return A simple JSON value.
296+ */
297+ public static Object stringToValue (String string ) {
298+ if (string .equals ("" )) {
299+ return string ;
300+ }
301+ if (string .equalsIgnoreCase ("true" )) {
302+ return Boolean .TRUE ;
303+ }
304+ if (string .equalsIgnoreCase ("false" )) {
305+ return Boolean .FALSE ;
306+ }
307+ if (string .equalsIgnoreCase ("null" )) {
308+ return JSONObject .NULL ;
309+ }
310+
311+ // If it might be a number, try converting it. If that doesn't work,
312+ // return the string.
313+
314+ try {
315+ char initial = string .charAt (0 );
316+ boolean negative = false ;
317+ if (initial == '-' ) {
318+ initial = string .charAt (1 );
319+ negative = true ;
320+ }
321+ if (initial == '0' && string .charAt (negative ? 2 : 1 ) == '0' ) {
322+ return string ;
323+ }
324+ if ((initial >= '0' && initial <= '9' )) {
325+ if (string .indexOf ('.' ) >= 0 ) {
326+ return Double .valueOf (string );
327+ } else if (string .indexOf ('e' ) < 0 && string .indexOf ('E' ) < 0 ) {
328+ Long myLong = new Long (string );
329+ if (myLong .longValue () == myLong .intValue ()) {
330+ return new Integer (myLong .intValue ());
331+ } else {
332+ return myLong ;
333+ }
334+ }
335+ }
336+ } catch (Exception ignore ) {
337+ }
338+ return string ;
339+ }
340+
341+
288342 /**
289343 * Convert a well-formed (but not necessarily valid) XML string into a
290344 * JSONObject. Some information may be lost in this transformation
0 commit comments