Sending Javascript functions using JSON and Java
I originally got my inspiration from this article on how to send Javascript functions over JSON and most of this work here is based on it.
By default every string attribute specified inside a JSON string is bounded by double quotes which works fine most of the time except when you are trying to pass a Javascript function in which case you have a string but it needs to be without double quotes.
Every JSON implementations that I’ve seen (both in PHP and Java) does not allow this in that every string is returned bounded by double quotes.
So short of implementing my own JSON tools in Java my only solution was to somehow work around the results products by the various JSON implementations.
The essence of our solution is to append some unique string values to the beginning and end of our Javascript function name and then remove these and attached quotes from our resulting JSON output.
I wrote a simple wrapper around the GSON implementation to do this:
-
-
import com.google.gson.Gson;
-
import com.truecool.stagetwo.utils.StringUtils;
-
-
public class GsonUtils {
-
// Magic strings are delimiters used to denote the start and end of a string
-
// you don’t want bounded by double quotes in the resulting json string
-
-
Gson gson = new Gson();
-
-
json = StringUtils.searchAndReplace(json, "\"" + MAGIC_STRING_START, "");
-
json = StringUtils.searchAndReplace(json, MAGIC_STRING_END + "\"", ""); return json;
-
}
-
}
-
Standard GSON/JSON up to the point where we replace our double quotes and magic strings with an empty string (“”).
To properly invoke the serialization method I use a map which I stuff with a value that surrounds my actual function name with the magic strings as follows:
-
-
…
-
// getAttributes() is a map
-
getAttributes().put(READYCALLBACK,
-
GsonUtils.MAGIC_STRING_START + readyCallback + GsonUtils.MAGIC_STRING_END);
-
}
-
…
-
Which in turn produces this; notice that someFunction is a string without double quotes.
-
-
{"elementId":"test","height":100,"readyCallback":someFunction,"width":"80%"…
-