Search code examples
javajsonrest-assured

RestAssured: posting json request having both String and Integer


I just want to POST json request(using restassured), for such json:

{
 "userId": 1,
 "id": 111,
 "title":"test msg"
 "body": "this is test msg"
}

Im defining base uri, and trying to use hashmap:

RestAssured.baseURI = "http://localhost:8888";
RestAssured.basePath = "/posts/";

Map<String, String> map = new HashMap<String, String>();
map.put("userId", 1);
map.put("id", 111);
map.put("title","test Post");
map.put("body","this is test body");

And of course its "red", because of trying put integer as string.

I'm changing to String.valueOf() for my 1 and 111 numbers,

then successfully posting request with smth like

 given()
    .contentType("application/json")
    .body(map)
    .when()
    .post("/")
    .then()
    .statusCode(201);

But response is incorrect(comparing with needed json):

{
    "id": "111",
    "title": "test Post",
    "body": "this is test body",
    "userId": "1"
}

2 points here:

- id and userId posted as Strings
- order is incorrect

So, question: what is the best approach in such situations, to correctly post needed request, in correct order and with int values for id and usedId?

Thanks!


Solution

  • What you can do is use Map<String, Object> instead of Map<String,String>. Also, the order is not preserved for the JSON Object. You cannot and should not rely on the ordering of elements within a JSON object.

    An object is an unordered set of name/value pairs. You can check out JSON specification for more info.