Thushar P Sujir
Thushar P Sujir

Reputation: 201

How to display backslash in json object value in java - Illegal escape JSONException

How to display a backslash in json value in java. I get a org.json.JSONException: Illegal escape. at 9 with the below sample code. I'm using json 1.0.0 jar - org.json

    String s1 = "{'Hi':'\\ksdfdsfsdfdfg'}";
    int i = (int) '/';
    System.out.println(s1);
    try
    {
        JSONObject json = new JSONObject(s1);
    }
    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 2

Views: 2368

Answers (3)

David Conrad
David Conrad

Reputation: 16359

You need two backslashes to produce one backslash in a Java string literal "\\", and you need to double the backslash to get a backslash in the JSON string (since JavaScript has similar rules about backslash escapes and string literals as Java), thus, you need four backslashes:

String s1 = "{'Hi':'\\\\ksdfdsfsdfdfg'}";

If you do this:

String s1 = "{'Hi':'\\\\ksdfdsfsdfdfg'}";
try {
    JSONObject json = new JSONObject(s1);
    System.out.println(json.get("Hi"));
} catch (JSONException e) {
    e.printStackTrace();
}

It prints:

\ksdfdsfsdfdfg

Upvotes: 1

Isuru
Isuru

Reputation: 722

You have to add 4 backslashes for this to work. If you just print the parsed json object value you will see 2 backslashes. But if you get the value from the JSONObject you will see only one.

String s1 = "{'Hi':'\\\\ksdfdsfsdfdfg'}";
int i = (int) '/';
System.out.println(s1);
try {
    JSONObject json = new JSONObject(s1);
    System.out.println(json);//this will print two backslashes

    String s = (String) json.get("Hi");
    System.out.println(s);//this will print only one
} catch (JSONException e) {
    e.printStackTrace();
}

Upvotes: 0

Michel_T.
Michel_T.

Reputation: 2821

I think, you use wrong quotation marks, use double quotation mark in JSON:

String s1 = "{\"Hi\":\"\\ksdfdsfsdfdfg\"}"

That should work.

Upvotes: 0

Related Questions