4

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 ?

Community
  • 1
  • 1
George Profenza
  • 50,687
  • 19
  • 144
  • 218
  • What has this to do with JavaScript? – Teemu Sep 13 '15 at 15:12
  • 1
    The JSON part mostly. I didn't mention in my question that I would normally receive this string from Javascript (websocket), where my main java code would be a basic Websocket Server. I didn't want to overcomplicate things, since this revolves mostly around JSON parsing in java – George Profenza Sep 13 '15 at 15:14
  • 1
    Note that `obj.get("property:")` would return a properly decoded `String` value, ie. one where the `\n` in JSON becomes a newline character. – Sotirios Delimanolis Sep 13 '15 at 15:35

1 Answers1

3

As you can see in the JSON specification, JSON does not allow real line breaks in strings, so you always need to escape newline characters with \n. This is not a special Java thing. See also this question.

Community
  • 1
  • 1
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51