简体   繁体   中英

Can't not pass a Json Array as body in Restassured request - java.lang.IllegalStateException: Not a JSON Object

I am trying to pass a list of objects as body in a restassured request:

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

But when I send the request I get:

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)

I already tried with JSONArray jsonArray = new JSONArray(transactionList) without success looking the request like this:

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
}

Because transactionList is an instance of List , while JSON requires key:value pairs, so you need to use a Map for generating proper payload. The simplest way in your case is:

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

This will send your body for sure, but you should play around and fit it depending on your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM