Building a nested JSONObject

大城市里の小女人 提交于 2020-06-17 07:24:06

问题


Below is the code I am using

    JSONObject requestParams = new JSONObject();

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

This is how the API needs to be posted

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

I get an error stating that "The another.child field is required."

How do I go about posting this via restAssured? The other APIs that do not require posting with nesting work, so I'm assuming that's why it's failing.


回答1:


What you posted was this since JSONObject has no notion of dot-separated key paths.

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

You need to make another JSONObject

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



回答2:


You can create a request object and then let the RestAssured library to serialise the object to json for you.

So for example:

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

..and then in a test method

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

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

Just don't forget the line contentType("application/json") so that the library knows you want to use json.

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



来源:https://stackoverflow.com/questions/48950819/building-a-nested-jsonobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!