Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add function to json object without using quotes.

I'm building a json object in java. I need to pass a function into my javascript and have it validated with jquery $.isFunction(). The problem I'm encountering is I have to set the function in the json object as a string, but the json object is passing the surrounding quotes along with object resulting in an invalid function. How do I do this without having the quotes appear in the script.

Example Java

JSONObject json = new JSONObject();
json.put("onAdd", "function () {alert(\"Deleted\");}");

Jquery Script

//onAdd output is "function () {alert(\"Deleted\");}" 
//needs to be //Output is function () {alert(\"Deleted\");} 
//in order for it to be a valid function.
if($.isFunction(onAdd)) { 
    callback.call(hidden_input,item);
}

Any thoughts?

like image 722
Code Junkie Avatar asked Dec 13 '22 01:12

Code Junkie


2 Answers

You can implement the JSONString interface.

import org.json.JSONString;

public class JSONFunction implements JSONString {

    private String string;

    public JSONFunction(String string) {
        this.string = string;
    }

    @Override
    public String toJSONString() {
        return string;
    }

}

Then, using your example:

JSONObject json = new JSONObject();
json.put("onAdd", new JSONFunction("function () {alert(\"Deleted\");}"));

The output will be:

{"onAdd":function () {alert("Deleted");}}

As previously mentioned, it's invalid JSON, but perhaps works for your need.

like image 72
Mike Avatar answered Dec 24 '22 10:12

Mike


You can't. The JSON format doesn't include a function data type. You have to serialise functions to strings if you want to pass them about via JSON.

like image 34
Quentin Avatar answered Dec 24 '22 09:12

Quentin