【问题标题】:Can't not pass a Json Array as body in Restassured request - java.lang.IllegalStateException: Not a JSON Object不能在再保证请求中将 Json 数组作为正文传递 - java.lang.IllegalStateException:不是 JSON 对象
【发布时间】:2021-02-12 20:02:40
【问题描述】:

我正在尝试在放心的请求中将对象列表作为正文传递:

Transaction transaction1 = new Transaction();
Transaction transaction2 = new Transaction();
List<Transaction> transactionList = new ArrayList<Transaction>();

transaction1.setTransactionType= "TRANS";
transaction1.setAmmount=12;

transaction2.setTransactionType= "EXTR";
transaction2.setAmmount=15;

transactionList.add(transaction1);
transactionList.add(transaction2);

given().contentType(ContentType.JSON)
       .body(transactionList).when()
       .post(http://localhost:8085/transactions/batch);

但是当我发送请求时,我得到:

Not a JSON Object: [{"transactionType":"TRANS","amount":"12"}, {"transactionType":"EXTR","amount":"15"}]
java.lang.IllegalStateException: Not a JSON Object: [{"transactionType":"TRANS","amount":"12"}, {"transactionType":"EXTR","amount":"15"}]   at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:91)

我已经尝试过使用JSONArray jsonArray = new JSONArray(transactionList),但没有成功,看起来像这样的请求:

2021-02-12 20:45:42,927 [Test worker] INFO  org.fpsautomation.loggerextension.LogFilter - Request details:
POST http://localhost:8085/transactions/batch 
Accept=*/*
Content-Type=application/json; charset=UTF-8
Params: {} 
Request body: {
  "empty": false
}

【问题讨论】:

  • 预期的请求负载是多少?也在这里发布 POJO

标签: java json rest-assured json-serialization


【解决方案1】:

因为transactionListList 的一个实例,而JSON 需要key:value 对,因此您需要使用映射来生成正确的有效负载。 在您的情况下,最简单的方法是:

Map<Object, Object> payload = new HashMap<>();
payload.put(transactionList, "");

这肯定会发送您的身体,但您应该根据自己的需要玩耍并适应它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多