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 str
(String string)
| 302 | * @return A simple JSON value. |
| 303 | */ |
| 304 | public static Object stringToValue(String string) { |
| 305 | if (string.equals("")) { |
| 306 | return string; |
| 307 | } |
| 308 | if (string.equalsIgnoreCase("true")) { |
| 309 | return Boolean.TRUE; |
| 310 | } |
| 311 | if (string.equalsIgnoreCase("false")) { |
| 312 | return Boolean.FALSE; |
| 313 | } |
| 314 | if (string.equalsIgnoreCase("null")) { |
| 315 | return JSONObject.NULL; |
| 316 | } |
| 317 | |
| 318 | // If it might be a number, try converting it. If that doesn't work, |
| 319 | // return the string. |
| 320 | |
| 321 | try { |
| 322 | char initial = string.charAt(0); |
| 323 | boolean negative = false; |
| 324 | if (initial == '-') { |
| 325 | initial = string.charAt(1); |
| 326 | negative = true; |
| 327 | } |
| 328 | if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { |
| 329 | return string; |
| 330 | } |
| 331 | if ((initial >= '0' && initial <= '9')) { |
| 332 | if (string.indexOf('.') >= 0) { |
| 333 | return Double.valueOf(string); |
| 334 | } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { |
| 335 | Long myLong = new Long(string); |
| 336 | if (myLong.longValue() == myLong.intValue()) { |
| 337 | return new Integer(myLong.intValue()); |
| 338 | } else { |
| 339 | return myLong; |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | } catch (Exception ignore) { |
| 344 | } |
| 345 | return string; |
| 346 | } |
| 347 | |
| 348 | |
| 349 | /** |