Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. This is much less ambitious than JSONObject.stringToValue, especially because it does not attempt to convert plus forms, octal forms, hex forms, or E forms lacking decimal points. @param st
(String string)
| 310 | * @return A simple JSON value. |
| 311 | */ |
| 312 | public static Object stringToValue(String string) { |
| 313 | if ("true".equalsIgnoreCase(string)) { |
| 314 | return Boolean.TRUE; |
| 315 | } |
| 316 | if ("false".equalsIgnoreCase(string)) { |
| 317 | return Boolean.FALSE; |
| 318 | } |
| 319 | if ("null".equalsIgnoreCase(string)) { |
| 320 | return JSONObject.NULL; |
| 321 | } |
| 322 | |
| 323 | // If it might be a number, try converting it, first as a Long, and then |
| 324 | // as a |
| 325 | // Double. If that doesn't work, return the string. |
| 326 | |
| 327 | try { |
| 328 | char initial = string.charAt(0); |
| 329 | if (initial == '-' || (initial >= '0' && initial <= '9')) { |
| 330 | Long value = Long.valueOf(string); |
| 331 | if (value.toString().equals(string)) { |
| 332 | return value; |
| 333 | } |
| 334 | } |
| 335 | } catch (Exception ignore) { |
| 336 | try { |
| 337 | Double value = Double.valueOf(string); |
| 338 | if (value.toString().equals(string)) { |
| 339 | return value; |
| 340 | } |
| 341 | } catch (Exception ignoreAlso) { |
| 342 | } |
| 343 | } |
| 344 | return string; |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Convert a well-formed (but not necessarily valid) XML string into a |