【问题标题】:Building a nested JSONObject构建嵌套的 JSONObject
【发布时间】:2018-02-23 15:07:58
【问题描述】:

下面是我正在使用的代码

    JSONObject requestParams = new JSONObject();

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

这就是 API 需要发布的方式

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

我收到一条错误消息,指出“需要另一个.child 字段。”

如何通过 restAssured 发布此内容?其他不需要发布嵌套工作的 API,所以我假设这就是它失败的原因。

【问题讨论】:

    标签: java json rest-assured web-api-testing rest-assured-jsonpath


    【解决方案1】:

    您发布的是因为JSONObject 没有点分隔键路径的概念。

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

    你需要再发一个JSONObject

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

    【讨论】:

      【解决方案2】:

      您可以创建一个请求对象,然后让 RestAssured 库为您将对象序列化为 json。

      例如:

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

      ..然后在测试方法中

      @Test
      public void itWorks() {
      ...
              Request request = new Request("something value", new Another("child value"));
      
              given().
                      contentType("application/json").
                      body(request).
              when().
                      post("/message");
      ...
      }
      

      请不要忘记contentType("application/json") 这行代码,以便库知道您要使用 json。

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

      【讨论】:

      • 我认为大多数序列化库都需要一个无参数构造函数才能工作
      • 对于使用 Jackson 从 Java 到 json 的序列化,您只需要 getter(或公共字段)。但需要反过来。
      猜你喜欢
      • 2011-03-09
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2016-03-03
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多