tags:

views:

113

answers:

4

I'm using the net.sf.json.JSONObject to create some data to be sent to a front end application, and the code I'm interacting with doesn't like the ways its adding quotation marks to every field name.

For example:

 myString = new JSONObject().put("JSON", "Hello, World!").toString();

produces the string {"JSON": "Hello, World"}.

What I want it to return is {JSON: "Hello, World"} - without quotes around "JSON". What do I have to do to make that happen?

A: 

Can I ask why you want to do this? It's not going to save thát much of the total bytes being transfered in the request.

In any case, I'd say you have to write something, a regexp or something else, that replaces /\"([^"]+)\"\:/ to the first match $1. I'm not fluent in Java so I can't actually help any more.

CharlesLeaf
I'm trying to change some back-end code without screwing around much with the front-end... and the front end doesn't seem to like quotation marks. So I'm just trying to give the front-end what it wants.
Spike Williams
Seems like a bug in the front-end. But in any case, my regular expression should be able to help you out. Replace `\"([^"]+)\"\:` with `$1:` in whatever way that should work in Java. `$1` would match, in your example `JSON`.
CharlesLeaf
+1  A: 

The javadoc says

The texts produced by the toString methods strictly conform to the JSON sysntax rules.

If you want to conform to the JSON syntax rules, you shouln't remove the quotes.

Or if you don't care about the rules, you could create you own simple method to contruct this strings.

Also, replace the 2 first occurrences of the quotes is valid, as @CharlesLeaf said.

Tom Brito
+1  A: 

The JSON definition describes each pair as a string : value, so you can't expect the net.sf libraries to contravene that particular contract. If you're worried about being able to access the values when they're returned to some javascript code (if that is what you're doing), you needn't be.

var str = {"JSON": "Hello, World"};
var obj = eval(str);
alert(obj.JSON); // Alerts "Hello, World"
unsquared
A: 

You can use the following method to exclude quotes from the property name in your json :

net.sf.json.util.WebUtils.toString(JSONObject);

Refer to the java doc :

http://json-lib.sourceforge.net/apidocs/net/sf/json/util/WebUtils.html#toString%28net.sf.json.JSON%29

Shrinidhi Shastri