4

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?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

5 Comments

Could you provide an example?
What you have is an example of that.
how do you convert it back to a function in the script?
Retrieve the string from the json object and use eval() on the string?
That seems to be the trick, I'm just concerned it won't work in some browsers. I'm just going to pass the function name into the json object, so hopefully there will be less bugs.
1

Running

onAdd = eval(onAdd);

should turn your string into a function, but it's buggy in some browsers.

The workaround in IE is to use

onAdd = eval("[" + onAdd + "]")[0];

See Are eval() and new Function() the same thing?

2 Comments

hmm so nothing stable, what about just removing the start and end quotes?
@George, if you remove the quotes, it's not JSON. However, If you are rendering the HTML in Java using the JSON object, you can just out.println(json.get("onAdd")) and it would print without quotes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.