Spring Rest模板发送JsonArray

时间:2014-02-21 06:39:27

标签: 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";
}

接受请求:

@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;
    }

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

3 个答案:

答案 0 :(得分:3)

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

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

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

  

java.lang.String toString()

      Make a JSON text of this JSONArray.

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

或改为Jackson实施Spring对此有所支持。 XD

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

<强>更新

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

更新2 将端点更改为。

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

答案 1 :(得分:1)

你需要为你的resttemplate配置httpmessageconverter,请阅读我为你的webservice配置http消息转发器的帖子

http://stackoverflow.com/questions/19963127/new-to-spring-and-jackson-2-what-does-this-bean-declaration-allow-for-in-a-spri/19973636#19973636.

对于将http请求转换为json的问题,您可以在restemplate配置中添加此条目

 <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

答案 2 :(得分:0)

错误非常简单。您没有JSONArray的转换器。将数组转换为String(使用toString)确实对您有帮助,但有更好的方法:

只需为json.org对象添加转换器:

将其添加到您的pom.xml

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-json-org</artifactId>
    </dependency>

然后在你的ObjectMapper上添加JsonOrgModule:

mapper.registerModule(new JsonOrgModule());