user2475664
user2475664

Reputation: 155

JSON Object creation fails when instantiated with a string with backslashes

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!

Upvotes: 3

Views: 4994

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

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

String str = "{\"path\":\"folderA\\\\myfileA\"}";

Upvotes: 4

Related Questions