Reputation: 201
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
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
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
Reputation: 2821
I think, you use wrong quotation marks, use double quotation mark in JSON:
String s1 = "{\"Hi\":\"\\ksdfdsfsdfdfg\"}"
That should work.
Upvotes: 0