Saqib Ahmed Saqib Ahmed - 23 days ago 6
Java Question

How to put value in JSONObject without quotations

I am working on a project using Alpacajs forms, creating schema JSON on java, now I need to make a json which have value with not double quotations like:

"buttons": {
"submit": {
"click": function() {
this.refreshValidationState(true);
if (!this.isValid(true)) {
this.focus();
return;
}
this.ajaxSubmit();
}
}
}


here is my code:

JSONObject ob = new JSONObject();
JSONObject button = new JSONObject();
JSONObject submit = new JSONObject();
submit.put("click", "function() {"
+"this.refreshValidationState(true);"
+"if (!this.isValid(true)) {"
+" this.focus();"
+" return;"
+"}"
+"this.ajaxSubmit();"
+"}");
button.put("submit", submit);
ob.put("buttons", button);


but I'm getting this:
after calling toJSONString();

"buttons": {
"submit": {
"click": "function() {this.refreshValidationState(true);if (!this.isValid(true)) { this.focus(); return;}this.ajaxSubmit();}"
}


It has double quotes and javascript is not working on it, how can I remove that double quotes from JSONObject using toJSONString() method.
any Idea.

Thanks.

Answer

I have worked on it and go through the source code of JSONObject, got an Idea and solve the problem.

JSONObject is adding quotations on String but not on Object, so I made a class,

public class Method implements java.io.Serializable{

    /** use serialVersionUID for interoperability */
    private static final long serialVersionUID = 1L;

    String value;

    public Method(String value) {
        super();
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString(){
        return this.value;
    }
}

And made the object of that class like this:

        JSONObject submit = new JSONObject();
        JSONObject button = new JSONObject();
        String value = "function() {"
                +"this.refreshValidationState(true);"
                +"if (!this.isValid(true)) {"
                +"     this.focus();"
                +"    return;"
                +"}"
                +"this.ajaxSubmit();"
                +"}";
        Method click =new Method(value);
        submit.put("click", click);
        button.put("submit", submit);
        button.toJSONString();

Now the problem is solved and code is working fine, and the output is as I need.

    "buttons": {
        "submit": {
            "click": function() {
                this.refreshValidationState(true);
                if (!this.isValid(true)) {
                    this.focus();
                    return;
                }
                this.ajaxSubmit();
            }
        }
    }