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.
source share