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?
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
org.json.simple.JSONObject.escape()
escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.
import org.json.simple.JSONValue;
JSONValue.escape("test string");
json-simple
homeAdd pom.xml when using maven
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<scope>test</scope>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With