2

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();
    }
1
  • 1
    Double it, so \\\\ Commented Jun 28, 2018 at 7:20

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

That would give an output with 2 backslashes. I needed only 1.
@ThusharPSujir No, that would give an output with 1 backslash.
0

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

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

That should work.

6 Comments

Yes, because you escaped the slash only for java, to do it also for the json, try use four slashes: "{\"Hi\":\"\\\\ksdfdsfsdfdfg\"}"
Yes but the thing is if I use 4 i get 2 backslashes I need only 1.
You get it in a parsed JSON or in your output from System.out.println(s1); ?
{"Hi":"\\ksdfdsfsdfdfg"} - sysout(String)------ {"Hi":"\\ksdfdsfsdfdfg"} - sysout(json)
If you retrieve the value from the map you will only see 1 backslash. String s = (String) json.get("Hi");
|
0

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();
}

Comments

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.