Java向json对象添加函数而不使用引号。
我正在java中构建一个json对象。 我需要将一个函数传递给我的javascript并使用jquery $ .isFunction()进行validation。 我遇到的问题是我必须将json对象中的函数设置为字符串,但json对象将周围的引号与对象一起传递,从而导致函数无效。 如何在脚本中没有引号的情况下执行此操作。
示例Java
JSONObject json = new JSONObject(); json.put("onAdd", "function () {alert(\"Deleted\");}");
Jquery脚本
//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); }
有什么想法吗?
运行
onAdd = eval(onAdd);
应该把你的字符串变成一个函数,但在某些浏览器中它是错误的。
IE中的解决方法是使用
onAdd = eval("[" + onAdd + "]")[0];
请参阅Eval()和新函数()是否相同?
您可以实现JSONString接口。
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; } }
然后,使用您的示例:
JSONObject json = new JSONObject(); json.put("onAdd", new JSONFunction("function () {alert(\"Deleted\");}"));
输出将是:
{"onAdd":function () {alert("Deleted");}}
如前所述,它是无效的JSON,但可能适合您的需要。
你不能。 JSON格式不包含函数数据类型。 如果要通过JSON传递函数,则必须将函数序列化为字符串。