How to handle Unterminated string exception correctly?

I am using the JSON.org java library to mess with.

I am currently encountering a \ncharacter error :

try{
            String s = "{\"property:\":\"line1\n,line2\"}";
            JSONObject o = new JSONObject(s);
        }catch(Exception e){
            e.printStackTrace(System.err);
        }

leads to:

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 indicates that my string should be escaped like this:

String s = "{\"property:\":\"line1\\n,line2\"}";

I would no longer see the exception and could replace the string "\n"with '\n', but I'm just wondering:

- recommended way to work with newlines in a JSON string in java?

+4
source share
1 answer

JSON, JSON , \n. Java. . .

+3

Source: https://habr.com/ru/post/1607169/


All Articles