如何使用可放心的方式将Json转换为Java以发出POST请求

问题描述 投票:0回答:1

我想使用下面的有效负载发布下面的请求,并寻找一种更好的方法来实现此功能,而不是使用转义字符来发布它。

“ {\ n” +“ \ t \” name \“:\” nameValue \“,\ n” +“ \ t \” age \“:\” ageValue \“,\ n” +“ \ t \ “ sex \”:\“ sexValue \”,\ n“ +” \ t \“ mobile \”:\“ mobileVal-uk \”,\ n“ +” \ t \“代码\”:[\ n“ + “ \ t \ t \” 8567 \“ \ n” +“ \ t] \ n” +“}”;

我想在下面使用类似的东西,例如arraylist,jsonObject,hashmap或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);
}
java rest-assured
1个回答
1
投票

我建议使用类似Jackson的库。您可以创建一个POJO来表示您的JSON对象,这将使您可以轻松地在JSON和Java对象之间切换。这将为您省去很多麻烦,而且您不必担心所有这些糟糕的格式:)

这里是更深入的教程-https://mkyong.com/java/jackson-how-to-parse-json/

© www.soinside.com 2019 - 2024. All rights reserved.