无法在 Restassured 请求中将 Json 数组作为主体传递 - java.lang.IllegalStateException: Not a JSON Object

问题描述

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

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":"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
}

解决方法

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

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

这肯定会使您的身体变差,但您应该根据自己的需要随意调整并适应它。