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:

  1.  
  2. import com.google.gson.Gson;
  3. import com.truecool.stagetwo.utils.StringUtils;
  4.  
  5. public class GsonUtils {
  6. // Magic strings are delimiters used to denote the start and end of a string
  7. // you don’t want bounded by double quotes in the resulting json string
  8. public static final String MAGIC_STRING_START = "ycaBQm9T8UPT—";
  9. public static final String MAGIC_STRING_END = "—1IRJDEPhW";
  10.  
  11. public static String toJson(Object object) {
  12. Gson gson = new Gson();
  13. String json = gson.toJson(object);
  14.  
  15. json = StringUtils.searchAndReplace(json, "\"" + MAGIC_STRING_START, "");
  16. json = StringUtils.searchAndReplace(json, MAGIC_STRING_END + "\"", ""); return json;
  17. }
  18. }
  19.  

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:

  1.  
  2. public void setReadyCallback(String readyCallback) {
  3.    // getAttributes() is a map
  4.     getAttributes().put(READYCALLBACK,
  5.         GsonUtils.MAGIC_STRING_START + readyCallback + GsonUtils.MAGIC_STRING_END);
  6.   }
  7.  

Which in turn produces this; notice that someFunction is a string without double quotes.

  1.  
  2. {"elementId":"test","height":100,"readyCallback":someFunction,"width":"80%"
  3.  

RSS feed for comments on this post

Leave a Comment

*
To prove that you're not a bot, enter this code
Anti-Spam Image