Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java escape JSON String?

Tags:

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?

like image 322
Alosyius Avatar asked Sep 19 '13 15:09

Alosyius


2 Answers

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

  • GSON
  • Crockford's lib

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
like image 90
jabclab Avatar answered Sep 19 '22 17:09

jabclab


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 home
  • document

Add pom.xml when using maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>
like image 20
Yeongjun Kim Avatar answered Sep 19 '22 17:09

Yeongjun Kim