简体   繁体   中英

Post Json Array in Json Object via RestTemplate in Spring Boot

Im trying to post an array in a json object using RestTemplate

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

Here is my PostMapping Controller

@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();
}

And this my POJO

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

And Im getting 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\""
}

Try to configure your RestTemplate with a Json Message Converter.

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

You may refer this blog post for a detailed explanation

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

And then perform your rest call as below.You will no longer need to explicitly create a Json Object.

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

Changed resttemplate.exchange to resttemplate.postForObject. And also changed the method to return 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;
    }

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