Search code examples
javaspring-bootresttemplate

The JSON value could not be converted to System.String


I'm facing an issue with a POST request. It's pretty simple, actually, I just need to send a piece of date in json in the body of the application. However, I keep getting the message below:

The JSON value could not be converted to System.String

The complete error message is as follows:

400 Bad Request: [{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"xxx","errors":{"$.reconciliationDate":["The JSON value could not be converted to System.String. Path: $.fooDate | LineNumber: 0 | BytePositionInLine: 23."]}}]

I tried using LinkedMultiValueMap instead of JsonObject and it didn't work too. From the error I assume there's something wrong with the json I'm sending... the data is: {"fooDate":"2021-05-11"}. The complete code is:

public void foo(String fooDate){
        try{
            Token token = this.GetAccessToken();
            if(token == null){
                throw new Exception("Access token was null");
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.set("Authorization", "Bearer " + token.getAccess_token());

            JsonObject body = Json.createObjectBuilder()
                    .add("fooDate", fooDate).build();


            HttpEntity<Object> entity = new HttpEntity<>(body, headers);
            ResponseEntity<String> result = restTemplate.exchange(properties.getUri(),
                    HttpMethod.POST,
                    entity,
                    String.class);

            if(result.getStatusCode() != HttpStatus.OK){
                throw new Exception(String.format("Endpoint returned an unexpected status code : %d",
                        result.getStatusCode()));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

Solution

  • The answer was pretty simple, actually. While attempting to fix this I tried adding to the headers the following:

    headers.set("Content-Type", "application/json");
    

    And that changed nothing on the behavior. However, by adding the following the bug was fixed:

    headers.setContentType(MediaType.APPLICATION_JSON);
    

    Hope this help something else when facing a similar issue.