Home > OS >  Spring Rest Template remove quotes from request body in array
Spring Rest Template remove quotes from request body in array

Time:08-05

I would like to send request with request body:

{
"params": [1, 124, "ABC"]
}

My code:

        val headers = HttpHeaders()
        headers.contentType = MediaType.APPLICATION_JSON

        val arrayNode = JsonArray()
        arrayNode.add(1)
        arrayNode.add(124)
        arrayNode.add("ABC")
        val map: MultiValueMap<String, String> = LinkedMultiValueMap()
        map.add("params", arrayNode.joinToString())

        val request = HttpEntity<MultiValueMap<String, String>>(map, headers)

        val response = restTemplate.postForEntity(
            URL,
            request,
            String::class.java
        )
        return response.body

but its generate request body:

Request body: {"params":["1, 124, \"A\""]}

Is there any way to send request without quotes?

CodePudding user response:

In the comments I explained the reason why you see quotes in your request body.
Here is the code you can use to send body without quotes:

  Map<String, List> req = new HashMap<>();
            List list = new ArrayList<>();
            list.add(1);
            list.add(124);
            list.add("A");
            req.put("params", list);
            HttpEntity<Map> request = new HttpEntity<>(req, headers);        
            ResponseEntity<String> result = restTemplate.postForEntity(uri, request, String.class);

Using this code, your request body should look like this:

"params": [1, 124, "ABC"]
  • Related