将Graphql查询作为JSON字符串

时间:2016-09-17 19:12:22

标签: java json rest graphql

提前感谢您的帮助。我正在使用java中的testng测试GRAPHQL API。

我正在尝试将伪装成JSON的agraphQL对象作为帖子发送,但是当尝试将字符串打包为JSON对象时,我收到以下错误:

SyntaxError: Unexpected token B<br> &nbsp; &nbsp;at Object.parse (native)<br> &nbsp; &nbsp;at parse (/app/node_modules/body-parser/lib/types/json.js:88:17)<br> &nbsp; &nbsp;at /app/node_modules/body-parser/lib/read.js:116:18<br> &nbsp; &nbsp;at invokeCallback (/app/node_modules/raw-body/index.js:262:16)<br> &nbsp; &nbsp;at done (/app/node_modules/raw-body/index.js:251:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:307:7)<br> &nbsp; &nbsp;at emitNone (events.js:80:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:179:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:913:12)<br> &nbsp; &nbsp;at _combinedTickCallback (internal/process/next_tick.js:74:11)<br> &nbsp; &nbsp;at process._tickDomainCallback (internal/process/next_tick.js:122:9)

我想创建的JSON对象在这里:

"{\"query\":\"{marketBySlug(slug: \"Boston\") {countryCode}}\"}"

我已经发现我的问题是将波士顿标识为字符串的转义引号打破了内部构造的Graphql查询字符串,但我不确定如何解决此问题。

2 个答案:

答案 0 :(得分:2)

试试这个:

"{\"query\":\"{marketBySlug(slug: \\\"Boston\\\") {countryCode}}\"}"

答案 1 :(得分:1)

您应该使用参数化查询,而不是弄乱字符串和转义。您的代码将如下所示:

String query =
        "query MarketBySlug($slug: String!) {\n" +
        "  marketBySlug(slug: $slug) {\n" +
        "    countryCode\n" +
        "  }\n" +
        "}";

    Map<String, Object> variables = new HashMap<>();
    variables.put("slug", slug);

    given()
    .body(new QueryDto(query, variables))
    .when()
    .post("/graphql")
    .then()
    .contentType(JSON)
    .statusCode(HttpStatus.OK.value())
    .body("data.marketBySlug.countryCode", equalTo(countryCode));

QueryDto只是一个简单的dto,包含两个字段(查询和变量),setter和getter。