简体   繁体   中英

How to convert Json to Java for making POST request using rest assured

I would like to post below request using the below payload and looking for a better way to do this rather than posting it this way with escaping characters.

"{\\n" + "\\t\\"name\\": \\"nameValue\\",\\n" + "\\t\\"age\\": \\"ageValue\\",\\n" + "\\t\\"sex\\": \\"sexValue\\",\\n" + "\\t\\"mobile\\": \\"mobileVal-uk\\",\\n" + "\\t\\"codes\\": [\\n" + "\\t\\t\\"8567\\"\\n" + "\\t]\\n" + "}";

I would like using something like below eg arraylist, jsonObject, hashmap or jsonrray.

@Test
public void studentDetails() {    
RestAssured.baseURI = "  http://localhost:3000";    
JSONObject mainObject = new JSONObject();    
JSONArray array = new JSONArray();    
array.put(Integer.parseInt("codes"), "8567");    
JSONObject arrayItem = new JSONObject();    
arrayItem.put("name", "nameValue");    
arrayItem.put("age", "ageValue");    
arrayItem.put("sex", "sexValue");    
arrayItem.put("mobile", "mobileVal");    
mainObject.put(String.valueOf(array), arrayItem);
given()            
  .body(mainObject.toString())            
  .when() 
  .post("/posts")            
  .then()
  .assertThat()
  .statusCode(200)
  .contentType(ContentType.JSON);
}

I would recommend using a library like Jackson . You can create a POJO that will represent your JSON object which will allow you to go between JSON and Java objects easily. It will save you a lot of trouble and you won't have to worry about all of that awful formatting :)

Here is a more in depth tutorial - https://mkyong.com/java/jackson-how-to-parse-json/

转到http://www.jsonschema2pojo.org/并创建 POJO 并使用它们在对象中发送请求和响应。

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