【问题标题】:RestAssured: posting json request having both String and IntegerRestAssured:发布具有 String 和 Integer 的 json 请求
【发布时间】:2019-12-17 09:28:12
【问题描述】:

我只想 POST json 请求(使用放心),对于这样的 json:

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

我正在定义基本 uri,并尝试使用 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");

当然还有它的“红色”,因为尝试将整数作为字符串。

我正在为我的 1 和 111 数字更改为 String.valueOf(),

然后用 smth like 成功发布请求

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

但响应不正确(与需要的json相比):

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

这里有 2 分:

- id and userId posted as Strings
- order is incorrect

所以,问题: 在这种情况下,以正确的顺序以及 id 和 usedId 的 int 值正确发布所需请求的最佳方法是什么?

谢谢!

【问题讨论】:

  • 改用Map&lt;String, Object&gt; !?
  • 这部分工作 - 顺序仍然不正确
  • 一个 JSON 对象没有顺序 => 你绝不能依赖 JSON 对象中的数据顺序,它基本上是一个集合键值对。

标签: java json rest-assured


【解决方案1】:

您可以使用Map&lt;String, Object&gt; 而不是Map&lt;String,String&gt;。 此外,不会为 JSON 对象保留顺序。您不能也不应该依赖 JSON 对象中元素的顺序。

对象是一组无序的名称/值对。 您可以查看JSON specification 了解更多信息。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2012-12-14
    • 2021-07-08
    • 1970-01-01
    • 2014-09-17
    • 2020-12-11
    • 1970-01-01
    • 2019-03-18
    • 2015-05-04
    相关资源
    最近更新 更多