1

While passing one special use case of String to JSONArray, getting the below error as:

org.json.JSONException: Unterminated string at 25 [character 26 line 1]

My code is as below:

public Object parseResponse(String msg) {
        JSONArray taskVariables = null;
        try {
            if (!StringUtils.isEmpty(msg)) {
                taskVariables = new JSONArray(msg);
            } else {
                taskVariables = createJSONError("Blank or null JSON received.");
            }
        } catch (JSONException e) {
            
        }
      return taskVariables;
}

The input String to the above function is as below:

"[{\"Name\":\"test\\r\\\"}]"

It is parsing till the word "test\r" and the raising the exception while parsing \" which is at the end of the string.

What is the solution for this?

Amit Agarwal
  • 67
  • 1
  • 1
  • 12
  • Is that string the *actual* data, including all the backslashes, or is that just what you're seeing in a debugger? Can you provide a [mcve] with the JSON hard-coded? We can't really tell what the *actual* data is at the moment. – Jon Skeet Mar 24 '21 at 11:58
  • The Java string `"\\\""` would have the value `\"` which in terms of json would look like escaped double quotes so the parser wouldn't take that as the end of the string, hence the error. `...test\\r\"...` for(`...test\r`) or `...test\\r\\\\\"...` (for `...test\r\`) should be fine. – Thomas Mar 24 '21 at 12:00
  • The actual data is "[{"Name" : "test\r\"}]" – Amit Agarwal Mar 24 '21 at 12:01
  • @Thomas What will be solution for this ? – Amit Agarwal Mar 24 '21 at 12:02
  • Okay, so the actual data is invalid JSON. The solution for that is "don't try to parse invalid JSON". We can't really suggest anything more than that, as we don't know where the JSON comes from or why it's invalid. – Jon Skeet Mar 24 '21 at 12:04
  • 1
    Read the last part of my comment: use `"...\\\\\"..."`, i.e. 5 backslashes: 4 backslashes to get 2 in Java (and thus 1 in JSON) + 1 to escape the double quotes in Java. – Thomas Mar 24 '21 at 12:04

0 Answers0