Search code examples
javajsonnode.js

Java escape JSON String?


I have the following JSON string that i am sending to a NodeJS server:

String string = "{\"id\":\"" + userID + "\",\"type\":\"" + methoden + "\",\"msg\":\"" + msget + "\", \"name\":\"" + namnet + "\", \"channel\":\"" + activeChatChannel + "\", \"visitorNick\":\"\", \"agentID\":\" " + agentID + "\"}";

PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "utf-8"));
pw.println(string);

The problem becomes when the string msget contains the character " and '

On the NodeJS server i am parsing the JSON like this:

var obj = JSON.parse(message);

Any ideas how i can manage to send all characters without problems?


Solution

  • I would use a library to create your JSON String for you. Some options are:

    This will make dealing with escaping much easier. An example (using org.json) would be:

    JSONObject obj = new JSONObject();
    
    obj.put("id", userID);
    obj.put("type", methoden);
    obj.put("msg", msget);
    
    // etc.
    
    final String json = obj.toString(); // <-- JSON string