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.

2 Answers 2

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.

4
  • 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; } Dec 28, 2010 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, 2010 at 5:28
  • Per my question stackoverflow.com/questions/6155560/… - 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, 2011 at 20:06
  • I don't know, as I have only used json-lib casually (written benchmark code against it).
    – StaxMan
    May 27, 2011 at 22:18
4

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

1
  • 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. Dec 28, 2010 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.