如何在SPQR中使用JSON标量

时间:2019-02-28 13:03:41

标签: java graphql-java graphql-spqr

我想在服务类中返回JSON文字

@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;
}

上面的代码转义了响应中的所有引号

{
  "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\"    }  ]}"
  }
}

如何删除转义符?

2 个答案:

答案 0 :(得分:2)

GraphQL响应已经是JSON,因此显然必须适当地转义内部的任何字符串。 如果要向其中添加动态对象,则实际上必须返回一个对象,而不是字符串。该对象可以是任何具有正确结构的东西,可以是Map,Jackson的ObjectNode,Gson的JsonObject或POJO。

例如

@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;
}

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

答案 1 :(得分:0)

我认为@kaqqao的解决方案是最佳实践。但是,如果您只想返回一个简单的字符串,请使用旧的字符串替换:

return genratedSchema.replace("\\", "");