The JSON value could not be converted to System.String

Viewed 819

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

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.

Gson should work for this type of conversion. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

EDIT

I don't have code snippet as of now, will share soon, but for now can you try something like below and see if it works. Gson gson = new Gson(); String json = gson.toJson(obj); In this case it will be like:

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

Sorry, in case I misunderstood your requirement.

Related