Spring Rest 模板发送 JsonArray

Use*_*ser 2 spring resttemplate

我正在使用 Spring Rest 模板根据请求发送 json 数组。发送请求的源码如下:

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";
}
Run Code Online (Sandbox Code Playgroud)

并接受请求:

@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;
    }
Run Code Online (Sandbox Code Playgroud)

问题是它给了我以下错误:无法写入请求:没有找到适合请求类型[org.json.JSONArray]的合适的HttpMessageConverter。任何建议都是可以接受的。

Koi*_*oer 5

JSONArray 没有 MessageConverter,因此我建议执行以下操作。

HttpEntity<JSONArray> entity = new HttpEntity<JSONArray>(jsonArray, headers);
Run Code Online (Sandbox Code Playgroud)

将 JSONArray 类转换为 String,并将其添加到 HttpEntity,您知道使用 toString

java.lang.String toString()

      Make a JSON text of this JSONArray.
Run Code Online (Sandbox Code Playgroud)

HttpEntity 实体 = new HttpEntity(jsonArray.toString(), headers);

或者更改为 Jackson 实现 Spring 对此有支持。XD

如果您不想执行上述操作,请考虑创建自己的 messageConverter 实现,这会起作用但更难

更新

HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
headers.setContentType(MediaType.APPLICATION_JSON);
Run Code Online (Sandbox Code Playgroud)

更新2将端点更改为。

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