POST Request in WebClient in Spring Boot and Receive responce as JSONObject

Viewed 10854

I am trying to make API POST Request with WebClient in Spring Boot. But I cannot to make a request and receive response as JSONObject. With RestTemplate I did it, recently I started to learn WebClient. So that I got stuck.

Error Spring gives: Error:(48, 28) java: incompatible types: no instance(s) of type variable(s) T exist so that reactor.core.publisher.Mono conforms to org.json.simple.JSONObject

Here is my source code:

Controller.java

        JSONObject jsonObject = new JSONObject();
        Turnover turnover = new Turnover();

               JSONObject resp = webClientBuilder.build()
                .post()
                .uri("http://180.12.10.10:8080/turnover/")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.APPLICATION_JSON )
                .body(Mono.just(turnover),Turnover.class)
                .retrieve()
                .bodyToMono(JSONObject.class);

Turnover.java


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class Turnover {

    private String start_date;
    private String end_date;
    private String account;

    public Turnover(){
        setStart_date("01.01.2020");
        setEnd_date("01.06.2020");
        setAccount("20296");
    }
}

Json I want to send

{
  "start_date":"01.01.2020",
  "end_date":"01.06.2020",
  "account":"20296"
}

Response API Returns:

{
    "status": 1,
    "message": "success",
    "data": [
        {
            "CODE_ACCOUNT": "20296",
            "CREDIT": 60610187386.86,
            "DEBIT": 60778253872.1
        }
    ]
}

Any Help is appreciated!

1 Answers

Most likely the issue is that you're asking for a string back but assigning it to a JSONObject. The exception seems odd and I'd expect a compilation error with what you have but try this:

  .bodyToMono(JSONObject.class)
  .block();

And you'll need to fix the content type on the request to be MediaType.APPLICATION_JSON so that it passes your object as json.

Related