|
26 | 26 | import java.util.Map; |
27 | 27 | import org.json.JSONArray; |
28 | 28 | import org.json.JSONException; |
29 | | -import org.json.JSONObject; |
| 29 | +import org.json.JSONTokener; |
30 | 30 |
|
31 | 31 | public class HttpRequestHandler { |
32 | 32 |
|
@@ -302,36 +302,25 @@ public static JSObject buildResponseHeaders(CapacitorHttpUrlConnection connectio |
302 | 302 | /** |
303 | 303 | * Returns a JSObject or a JSArray based on a string-ified input |
304 | 304 | * @param input String-ified JSON that needs parsing |
305 | | - * @return A JSObject or JSArray |
306 | | - * @throws JSONException thrown if the JSON is malformed |
| 305 | + * @return A JSObject, JSArray or literal |
307 | 306 | */ |
308 | | - public static Object parseJSON(String input) throws JSONException { |
309 | | - JSONObject json = new JSONObject(); |
| 307 | + public static Object parseJSON(String input) { |
310 | 308 | try { |
311 | | - if ("null".equals(input.trim())) { |
312 | | - return JSONObject.NULL; |
313 | | - } else if ("true".equals(input.trim())) { |
314 | | - return true; |
315 | | - } else if ("false".equals(input.trim())) { |
316 | | - return false; |
317 | | - } else if (input.trim().length() <= 0) { |
318 | | - return ""; |
319 | | - } else if (input.trim().matches("^\".*\"$")) { |
320 | | - // a string enclosed in " " is a json value, return the string without the quotes |
321 | | - return input.trim().substring(1, input.trim().length() - 1); |
322 | | - } else if (input.trim().matches("^-?\\d+$")) { |
323 | | - return Integer.parseInt(input.trim()); |
324 | | - } else if (input.trim().matches("^-?\\d+(\\.\\d+)?$")) { |
325 | | - return Double.parseDouble(input.trim()); |
326 | | - } else { |
| 309 | + // try to parse input as an object |
| 310 | + return new JSObject(input); |
| 311 | + } catch (JSONException e) { |
| 312 | + try { |
| 313 | + // fall through to try to parse it as an array |
| 314 | + return new JSArray(input); |
| 315 | + } catch (JSONException e2) { |
327 | 316 | try { |
328 | | - return new JSObject(input); |
329 | | - } catch (JSONException e) { |
330 | | - return new JSArray(input); |
| 317 | + // the value is probably a literal, so we can try to have the JSONTokener parse it for us |
| 318 | + return new JSONTokener(input).nextValue(); |
| 319 | + } catch (JSONException e3) { |
| 320 | + // if nothing could be parsed, return the input as is |
| 321 | + return input; |
331 | 322 | } |
332 | 323 | } |
333 | | - } catch (JSONException e) { |
334 | | - return input; |
335 | 324 | } |
336 | 325 | } |
337 | 326 |
|
|
0 commit comments