Search code examples
javajsonrest-assuredweb-api-testingrest-assured-jsonpath

Building a nested JSONObject


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.


Solution

  • 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);