构建嵌套的 JSONObject

Building a nested JSONObject

下面是我使用的代码

    JSONObject requestParams = new JSONObject();

    requestParams.put("something", "something value");
    requestParams.put("another.child", "child value");

这就是 API 需要发布的方式

{
   "something":"something value",
   "another": {
   "child": "child value"
   }
}

我收到一条错误消息,指出 "The another.child field is required."

我如何通过 restAssured 发布此信息?其他 API 不需要发布嵌套工作,所以我假设这就是它失败的原因。

您可以创建一个请求对象,然后让 RestAssured 库为您将该对象序列化为 json。

例如:

        class Request {
            private String something;
            private Another another;

            public Request(final String something, final Another another) {
                this.something = something;
                this.another = another;
            }

            public String getSomething() {
                return something;
            }

            public Another getAnother() {
                return another;
            }
        }

       class Another {
            private String child;

            public Another(final String child) {
                this.child = child;
            }

            public String getChild() {
                return child;
            }
        }

..然后在测试方法

@Test
public void itWorks() {
...
        Request request = new Request("something value", new Another("child value"));

        given().
                contentType("application/json").
                body(request).
        when().
                post("/message");
...
}

只是不要忘记行 contentType("application/json") 以便图书馆知道您要使用 json.

参见:https://github.com/rest-assured/rest-assured/wiki/Usage#serialization

你发布的是这个,因为 JSONObject 没有 dot-separated 关键路径的概念。

{
   "something":"something value",
   "another.child": "child value"
}

你需要再做一个JSONObject

JSONObject childJSON = new JSONObject():
childJSON.put("child", "child value");
requestParams.put("another", childJSON);