3

I have code, where I instantiate a JSONObject from a string. Upon instantiation, I get a JSONException Illegal escape. Any pointers on how to resolve this ?

Here is the block of code:

@Test
public void testJSONString()
{
    try
    {   
        String str = "{\"path\":\"folderA\\myfileA\"}";
        JSONObject jsonObj = new JSONObject(str);

    } catch (JSONException e)
    {
        e.printStackTrace();
        fail();
    }

}

The exception I get is:

org.json.JSONException: Illegal escape. at 18 [character 19 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONTokener.nextString(JSONTokener.java:289)
at org.json.JSONTokener.nextValue(JSONTokener.java:360)
at org.json.JSONObject.<init>(JSONObject.java:225)
at org.json.JSONObject.<init>(JSONObject.java:327)

Seems to be an issue with the \\m there. What would be the right way to escape this ?

Thanks!

1

1 Answer 1

4

The json should escape the backslashes like \\ so in Java both backslashes need escaped \\\\.

String str = "{\"path\":\"folderA\\\\myfileA\"}";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That makes it a little tricky now. The string that I have given above comes as part of a web service JSON response. I cannot just do a string replace to replace all \\ with \\\\. since \\n, \\r, \\b, \\t, \\f work, and \\ followed by all other characters dont. So regex might be the solution, and somehow regex and I arent the best of friends :(
@user2475664 Only sadistic people like regex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.