通过Spring Boot中的RestTemplate在Json对象中发布Json数组



我试图使用RestTemplate 在json对象中发布数组

{
"update": {
"name": "xyz",
"id": "C2",
"Description": "aaaaaa",
"members": ["abc", "xyz"]
}
}

这是我的PostMapping控制器

@PostMapping(value = "/update")
public Update update(@RequestBody Update update) {
String url = "";
HttpHeaders headers = createHttpHeaders("username", "passowrd");
JSONObject jsonObject = new JSONObject();
jsonObject.put("update", update);
HttpEntity<JSONObject> request = new HttpEntity<>(jsonObject, headers);
ResponseEntity<Update> update = restTemplate.exchange(url, HttpMethod.POST,request, Update.class);
return update.getBody();
}

这是我的POJO

public class Update {
private String name;
private String id;
private String Descripion;
private List<String> members;
}

我得到500

{
"timestamp": "2020-03-13T06:31:21.822+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No HttpMessageConverter for org.json.JSONObject and content type "application/json""
}

尝试使用Json消息转换器配置RestTemplate。

restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

你可以参考这篇博客文章来详细解释

https://www.baeldung.com/spring-httpmessageconverter-rest

然后按如下方式进行休息呼叫。您将不再需要显式地创建Json对象。

String url = "";
HttpEntity<Update> request = new HttpEntity<>(update, headers);
ResponseEntity<Update> firewallGroupUpdate = restTemplate.exchange(url, HttpMethod.POST, request, Update.class);
return firewallGroupUpdate.getBody();

已将resttemplate.exchange更改为resttemplate.postForObject。并且还将方法更改为返回String。

public String groupUpdate(@RequestBody String groupUpdate) {
String url = "";
HttpHeaders headers = createHeaders("username","password");
headers.setContentType(MediaType.APPLICATION_JSON);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<String> requestEntity = new HttpEntity<String>(groupUpdate, headers);
String response = restTemplate.postForObject(url,requestEntity,String.class);
return response;
}

最新更新