Serializing a non-JSON javascript object in java

Viewed 19

I have a java project where I am trying to serialize a javascript object that later needs to be viewed in a browser. I'd been using org.json.JSONObject to generate the javascript object, and that works great for basic json-friendly types. Recently I have a need to add javascript functions to the serialized javascript, but this JSONObject doesn't seem to offer a good path to serialize javascript functions.

I'd really like to end up with something like this:

{
  "foo": "bar",
  "baz": function (x, y) {
    return x+y;
  }
}

I'm happy to define some custom serializer in java for the function, but I've had trouble seeing how I could extend JSONObject to accomplish that. I have shamefully used this workaround for now, where I create a json structure of known shape...

{
  "foo": "bar",
  "baz": {
    "function": {
      "args": ["x", "y"],
      "body": "return x+y;"
    }
  }
}

...and then converting it to a real function on the browser client side. This seems to work, but I'd really prefer just more cleanly serializing the function in the first place.

From java, how can I serialize a javascript object that contains javascript functions?

0 Answers
Related