6

I am using JSON-lib library for java http://json-lib.sourceforge.net

I just want to add simple string which can look like JSON (but i do not want library to automatically figure out that it might be json and just to treat it as string). Looking into source of library I can't find the way to do it without ugly hacks.

example:

JSONObject object = new JSONObject();
String chatMessageFromUser = "{\"dont\":\"treat it as json\"}";
object.put("myString", chatMessageFromUser);

object.toString() will give us {"myString":{"dont":"treat it as json"}}

and i want just to have {"myString":"{\"dont\":\"treat it as json\"}"}

How to achieve it without modifying source code ? I am using this piece of code as transport for chat messages from users - so it works OK for normal chat messages, but when user will enter JSON format as message it will break it because of default behavior of JSON-lib described here.

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Mike Pandorium
  • 143
  • 2
  • 5

2 Answers2

5

If I understand question correctly, I think json-lib is unique in its assumption of a String being passed needing to be parsed. Other libs typically treat it as String to include (with escaping of double-quotes and backslashes as necessary), i.e. work as you would expect.

So you may want to consider other libraries: I would recommend Jackson, Gson also works.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • Correct, json-lib will always try first to parse the string: if( JSONUtils.isString( value ) ) { String str = String.valueOf( value ); if( JSONUtils.hasQuotes( str ) ){ String stripped = JSONUtils.stripQuotes( str ); if( JSONUtils.isFunction( stripped )){ ... } if(stripped.startsWith("[") && stripped.endsWith("]")) { ... } if(stripped.startsWith("{") && stripped.endsWith("}")) { ... } return str; } – Mike Pandorium Dec 28 '10 at 18:59
  • Ok. This is quite an interesting approach... it seems unintuitive to me, but maybe it was what worked for json-lib author's use cases. – StaxMan Dec 29 '10 at 05:28
  • Per my question http://stackoverflow.com/questions/6155560/how-to-force-json-libs-jsonobject-put-to-escape-a-string-containing-json - are we absolutely sure there's no way to accomplish this behavior with JSON-lib? I'd *really* like to avoid swapping out that dep. – Ben Burns May 27 '11 at 20:06
  • I don't know, as I have only used json-lib casually (written benchmark code against it). – StaxMan May 27 '11 at 22:18
4

json-simple offers a JSONObject.escape() method.

asthasr
  • 9,125
  • 1
  • 29
  • 43
  • I just rewrote the application with json-simple and it works great, you don't even have to escape() it, by default it treats string as string and not trying to parse it as JSON. Life is so much simple with json-simple. – Mike Pandorium Dec 28 '10 at 16:33