javagraphql-javagraphql-spqr

How to use JSON Scalar in SPQR


I want to return a JSON literal in the service class

@GraphQLQuery(name = "renderUI", description = "Schema for your form")
public String renderUI() {
     String genratedSchema = "{" +
            "  \"schema\": {" +
            "    \"type\": \"object\"," +
            "    \"id\": \"urn:jsonschema:profile:model:DemoForm\"," +
            "    \"properties\": {" +
            "      \"comment\": {" +
            "        \"type\": \"string\"," +
            "        \"title\": \"Comment\"" +
            "      }" +
            "    }" +
            "  }," +
            "  \"form\": [" +
            "    {" +
            "      \"key\": \"comment\"," +
            "      \"type\": \"textarea\"," +
            "      \"required\": false," +
            "      \"description\": \"Add your Comment here\"," +
            "      \"placeholder\": \"fill your comment please\"" +
            "    }" +
            "  ]" +
            "}";
    return  genratedSchema;
}

The above code is escaping all the quotes in the response

{
  "data": {
    "renderUI": "{  \"schema\": {    \"type\": \"object\",    \"id\": \"urn:jsonschema:com:fnstr:bankprofile:gppbankprofile:model:DemoForm\",    \"properties\": {      \"comment\": {        \"type\": \"string\",        \"title\": \"Comment\"      }    }  },  \"form\": [    {      \"key\": \"comment\",      \"type\": \"textarea\",      \"required\": false,      \"description\": \"Add your Comment here\",      \"placeholder\": \"fill your comment please\"    }  ]}"
  }
}

How to remove the Escape characters ?


Solution

  • A GraphQL response is already JSON, so any strings inside obviously need to be escaped appropriately. If you want to add dynamic object into it, you must actually return an object, not a string. The object can be anything that has the correct structure, could be a Map, Jackson's ObjectNode, Gson's JsonObject or a POJO.

    E.g.

    @GraphQLQuery(name = "renderUI", description = "Schema for your form")
    public Map<String, Object> renderUI() {
        Map<String, Object> dynamic = new HashMap<>();
        dynamic.put("schema", ...); //fill the whole structure
        return dynamic;
    }
    

    or

    @GraphQLQuery(name = "renderUI", description = "Schema for your form")
    public ObjectNode renderUI() {
        return ...;
    }