Search code examples
springresttemplate

Spring Rest Template to send JsonArray


I am using spring rest template to send json array as request. Source code to send request is as follow:

JSONArray jsonArray = new JSONArray();

for (Iterator iterator = itemlist.iterator(); iterator.hasNext();) {

    Item item = (Item)iterator.next();

    JSONObject formDetailsJson = new JSONObject();

    formDetailsJson.put("id", item.getItemConfId());
    formDetailsJson.put("name", item.getItems().getItemName());
    formDetailsJson.put("price", item.getPrice());
    formDetailsJson.put("Cost",item.getCost());

    jsonArray.put(formDetailsJson);
}


List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
// Pass the new person and header
HttpEntity<JSONArray> entity = new HttpEntity<JSONArray>(jsonArray, headers);

System.out.println("Json Object : "+entity);
// Send the request as POST
try {
    ResponseEntity<String> result = restTemplate.exchange("my url", HttpMethod.POST, entity, String.class);

} catch (Exception e) {
    logger.error(e);

    return "Connection not avilable please try again";
}

And to accept request:

@RequestMapping(value = "/testStock", method = RequestMethod.POST,headers="Accept=application/xml, application/json")
    public @ResponseBody int testStock(@RequestBody List<ItemList>  jsonArray) {

        logger.debug("Received request to connect ms access : "+jsonArray.size());

        //int returnSizecount = stockList.getStocklst().size();

        return 1;
    }

The problem is that it giving me following error: Could not write request: no suitable HttpMessageConverter found for request type [org.json.JSONArray].Any suggestion is greatly acceptable.


Solution

  • There are no MessageConverter for JSONArray, so I suggest do the following.

    HttpEntity<JSONArray> entity = new HttpEntity<JSONArray>(jsonArray, headers);
    

    Convert Class JSONArray to String, and add that to HttpEntity, you know use toString

    java.lang.String toString()

          Make a JSON text of this JSONArray.
    

    HttpEntity entity = new HttpEntity(jsonArray.toString(), headers);

    Or change to Jackson implementation Spring have support to that. XD

    If you dont want to do the above, consider create your own implementation of messageConverter, that will work but is harder

    update

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(acceptableMediaTypes);
    headers.setContentType(MediaType.APPLICATION_JSON);
    

    update 2 Change endpoint to.

    @RequestMapping(value = "/testStock", method = RequestMethod.POST)
        public @ResponseBody int testStock(@RequestBody String  jsonArray) {