Java adds a function to a json object without using quotes.

I am creating a json object in java. I need to pass a function to my javascript and test it with jquery $ .isFunction (). The problem I am facing is to set the function in the json object as a string, but the json object passes the surrounding quotes along with the object, which leads to an invalid function. How to do this if quotation marks are not displayed in the script.

Java example

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?

+4
source share
3 answers

Launch

 onAdd = eval(onAdd); 

should turn your string into a function, but it does not work in some browsers.

Workaround in IE is to use

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

See Is eval () and new function () the same?

+1
source

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 mentioned earlier, this is invalid JSON, but it may work for your needs.

+7
source

You can not. JSON format does not include function data type. You must serialize functions for strings if you want to pass them through JSON.

+3
source

Source: https://habr.com/ru/post/1415621/


All Articles