Search code examples
javajsonspring-bootspring-mvcresttemplate

How to get data json on RestTemplate when request to server


I'm using RestTemplate and JSONObject json to POST request to server. When I try to request on Postmen, it run success and return result 200(Ok), But when run my code it can not run

This is my format json:

{
 "senderUser": "user@gmail.com",
"data": [
{
  "actionType": "update-contact",
  "data": {
    "name": "luong van",
    "lastname": "khanh",
    "type": 0,
    "title": "",
    "passport": "",
    "gender": 1,
    "bgInfo": "",
    "dateOfBirth": "",
    "emails": [{"value": "user@gmail.com"}],
    "phones": [{"value": "0902032618"}],
    "addresses": [{"street": "10", "city":"Osaka", "state": "Osake", "country":       
        {"code":"JP", "name":"Japan"}}],
    "tag": ""
  }
}
 ]
}

This is my class:

public class InComingAPI {
private static Logger logger = LoggerFactory.getLogger(InComingAPI.class);

public static void main(String []args) {
    RestTemplate restTemplate = new RestTemplate();

    String url = "https://myservice/90336429462601e7f3326641898fabd9948b349d";

    try {
        logger.info("hi there");
        // RestTemplate restTemplate = new RestTemplate();
        // String url = "http://localhost:8181/xyz/updateAdmin";

        JSONArray json = new JSONArray();
        JSONObject obj = new JSONObject();

        obj.put("name", "khanh");
        obj.put("lastname", "luong van");
        obj.put("type", "0");
        obj.put("dateOfBirth", "");
        obj.put("emails", "user@gmail.com");
        obj.put("phones", "0902032618");
        obj.put("addresses", "Osaka");

        json.put(obj);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);
        String result = restTemplate.postForObject(url, json, String.class);
        System.out.println(result);
    }
    catch(Exception e) {
        e.printStackTrace();
    }
 }
}

and it happens an exception following as:

2021-01-22 17:50:17,280  INFO [com.outincoming.InComingAPI] hi there
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.json.JSONArray]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:787)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:566)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:329)
at com.outincoming.InComingAPI.main(InComingAPI.java:70)

How I can fix the problem ? many thank


Solution

  • Actually, the exception thrown is totally misleading. Turned out the problem is not that the MappingJackson2HttpMessageConverter didn't know how to marshall my object -which sounded strange, being JSON-, but a configuration of the underlying ObjectMapper.

    What I did is to disable the property SerializationFeature.FAIL_ON_EMPTY_BEANS like that

    public class InComingAPI {
    private static Logger logger = LoggerFactory.getLogger(InComingAPI.class);
    
    public static void main(String []args) {
        RestTemplate restTemplate = new RestTemplate();
        MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
        jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
    
        String url = "https://myservice/90336429462601e7f3326641898fabd9948b349d";
    
        try {
            logger.info("hi there");
            // RestTemplate restTemplate = new RestTemplate();
            // String url = "http://localhost:8181/xyz/updateAdmin";
    
            JSONArray json = new JSONArray();
            JSONObject obj = new JSONObject();
    
            obj.put("name", "khanh");
            obj.put("lastname", "luong van");
            obj.put("type", "0");
            obj.put("dateOfBirth", "");
            obj.put("emails", "user@gmail.com");
            obj.put("phones", "0902032618");
            obj.put("addresses", "Osaka");
    
            json.put(obj);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
    
            HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);
            String result = restTemplate.postForObject(url, json, String.class);
            System.out.println(result);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
     }