I'm using the JSON.org java library to tinker with.
At the moment I'm encountering an error because of \n
characters:
try{
String s = "{\"property:\":\"line1\n,line2\"}";
JSONObject o = new JSONObject(s);
}catch(Exception e){
e.printStackTrace(System.err);
}
results in:
org.json.JSONException: Unterminated string at 20 [character 0 line 2]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONTokener.nextString(JSONTokener.java:261)
at org.json.JSONTokener.nextValue(JSONTokener.java:361)
at org.json.JSONObject.<init>(JSONObject.java:218)
at org.json.JSONObject.<init>(JSONObject.java:325)
After doing a quick search I found this answer which points to my string having to be escaped like so:
String s = "{\"property:\":\"line1\\n,line2\"}";
I would no longer see the exception and could do a string replace for "\n"
with '\n'
, but I'm just wondering:
is the recommended way of dealing with new lines in a JSON string in java ?