1

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
M G
  • 47
  • 1
  • 7

2 Answers2

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
2

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);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245