Home > Blockchain >  Array format changes with WebClient Post is used
Array format changes with WebClient Post is used

Time:04-29

I am trying to send the below JSON via WebClient to an endpoint. I tried sending it as a POJO, a Map, and a JsonNode for the request body but the array is converted to the index-based format.

JSON to be sent;

{
   "jediId":"23",
   "name":luke,
   "master":"yoda",
   "address":[
      {
         "planet":"tatooine",
         "city":"mos eisley"
      }
   ],
   "filters":{
      "male":1,
      "female":1,
      "padawan":0,
      "master":1
   }
}

On the other side, the address is converted to address[0].planet=tatooine, address[0].city=mos eisley i.e the format changes

I created a JsonNode with the Jackson and printed the exact format but the array changes in the response.

public Jedi sendRequest(String url, JsonNode request) {
      return webClient.post()
                    .uri(url)
                    //.bodyValue(request)
                    .body(BodyInserters.fromValue(request))
    
                    .retrieve()
                    .bodyToMono(Jedi.class)
                    .blockOptional()
                    .orElseThrow();
     }
}

A similar format change happens to "filters" as well. For example, filters.male=1

I tried both body and bodyValue functions but the result is the same. I am missing something but could not figure out what it is. Any help would be great.

Thanks!

CodePudding user response:

You need to send it as a String that holds valid JSON format. SpringBoot uses JSON Jackson lib and will parse it. It is a responsibility of your SpringBoot end point to parse it. So, really you should ask person who developed the endpoint what info is expected. But in most cases it is String that holds valid json. It might be required that json conforms to particular schema but that is the info that should be included in your endpoint requirments

CodePudding user response:

Thanks to Michael for stating the point of using String in the request. I converted the whole JSON into a String but what I should have done was convert the "filters" and "address" into a String as well.

 private ObjectNode setRequestWithMapper() throws JsonProcessingException {
    ObjectNode request = objectMapper.createObjectNode();
    //other key values ..
    String AddressArrayStr = objectMapper.writeValueAsString(addressArray);
    String filterStr = objectMapper.writeValueAsString(filters);
    
    request.put("address", AddressArrayStr );
    request.put("filters", filtersStr);
    return request;
}

And for the body;

public Jedi sendRequest(String url, JsonNode request) {
      return webClient.post()
                    .uri(url)
                    .bodyValue(request)
                    .retrieve()
                    .bodyToMono(Jedi.class)
                    .blockOptional()
                    .orElseThrow();
     }
}
  • Related