Search code examples
javaspring-bootwebclient

Java Spring WebClient: Accept Json String in POST API


What is the proper way to use Spring Boot WebClient, and accept a json string into a POST Request? I am currently using code below .

I want to convert the string back into json, with certain Naming Json Properties. Currently just using ObjectMapper, and it works great. Not sure if there is more efficient way.

@Data
public class AccountRequest {
    @JsonProperty("event_header")
    private AccountEventHeader accountEventHeader;
    
    @JsonProperty("companyData")
    private List<CompanyData> companyRequestList;
}


    try {
        requestValue = objectMapper.writeValueAsString(accountRequest);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }

    ResponseEntity<String> responseData = this.webClient.post()
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(requestValue)
            .retrieve().toEntity(String.class)
            .block();

Solution

  • Since you use the String.class in toEntity(String.class) you get a string response instead you need to create a class which represents the response body example

    class ResponseData {
       String name;
       String age;
    }
    

    you need to use this class in

    ResponseEntity<ResponseData> responseData = this.webClient.post()
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(requestValue)
            .retrieve().toEntity(ResponseData.class)
            .block();
    ResponseData data = responseData.getBody();
            System.out.println("Name: " + data.getName());
            System.out.println("Age: " + data.getAge());