簡體   English   中英

Spring 3.0使用jackson消息轉換器進行JSON響應

[英]Spring 3.0 making JSON response using jackson message converter

我將我的messageconverter配置為傑克遜的

class Foo{int x; int y}

並在控制器中

@ResponseBody
public Foo method(){
   return new Foo(3,4)
}

從那個我期望從服務器返回一個JSON字符串{x:'3',y:'4'},沒有任何其他配置。 但得到我的ajax請求的404錯誤響應

如果使用@ResponseBody注釋該方法,則將返回類型寫入響應HTTP正文。 返回值將使用HttpMessageConverters轉換為聲明的方法參數類型。

我錯了嗎 ? 或者我應該使用序列化程序將我的響應對象轉換為Json字符串,然后將該字符串作為響應返回。(我可以正確地進行字符串響應)或者我應該進行其他配置嗎? 比如為Foo類添加注釋

這是我的conf.xml

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>

您需要以下內容:

  1. 設置注釋驅動的編程模型:在spring.xmlspring.xml <mvc:annotation-driven />
  2. 在類路徑中放置jaskson jar(Maven artifactId是org.codehaus.jackson:jackson-mapper-asl )。
  3. 使用如下:

     @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public @ResponseBody Foo method(@Valid Request request, BindingResult result){ return new Foo(3,4) } 

這適合我。

請注意,那

  1. @ResponseBody應用於返回類型,而不是方法定義。
  2. 你需要@RequestMapping注釋,以便Spring檢測它。

這對我有用:

@RequestMapping(value = "{p_LocationId}.json", method = RequestMethod.GET)
protected void getLocationAsJson(@PathVariable("p_LocationId") Integer p_LocationId,
     @RequestParam("cid") Integer p_CustomerId, HttpServletResponse response) {
        MappingJacksonHttpMessageConverter jsonConverter = 
                new MappingJacksonHttpMessageConverter();
        Location requestedLocation = new Location(p_LocationId);
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        if (jsonConverter.canWrite(requestedLocation.getClass(), jsonMimeType)) {
        try {
            jsonConverter.write(requestedLocation, jsonMimeType,
                                   new ServletServerHttpResponse(response));
            } catch (IOException m_Ioe) {
                // TODO: announce this exception somehow
            } catch (HttpMessageNotWritableException p_Nwe) {
                // TODO: announce this exception somehow
            }
        }
}

請注意,該方法不返回任何內容: MappingJacksonHttpMessageConverter#write()完成了魔術。

MessageConverter接口http://static.springsource.org/spring/docs/3.0.x/javadoc-api/定義了一個getSupportedMediaTypes()方法,在MappingJacksonMessageCoverter的情況下返回application / json

public MappingJacksonHttpMessageConverter() {
    super(new MediaType("application", "json", DEFAULT_CHARSET));
}

我假設缺少一個Accept:application / json請求標頭。

HTTP 404錯誤僅表示無法找到資源。 這可能有兩個原因:

  1. 請求URL錯誤(客戶端錯誤或給定鏈接/按鈕中的錯誤URL)。
  2. 資源不在您期望的位置(服務器端錯誤)。

要修復1,請確保您正在使用或提供正確的請求URL(區分大小寫!)。 要修復2,請檢查服務器啟動日志以查找任何啟動錯誤並相應地進行修復。

這一切都超出了迄今為止發布的代碼和信息。

我發現我也需要jackson-core-asl.jar,而不僅僅是jackson-mapper-asl.jar

除了這里的答案..

如果你在客戶端使用jquery,這對我有用:

Java的:

@RequestMapping(value = "/ajax/search/sync") 
public ModelAndView sync(@RequestBody Foo json) {

Jquery(你需要包含Douglas Crockford的json2.js來獲得JSON.stringify函數):

$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});

這只是一個猜測,但默認情況下,傑克遜只會自動檢測公共字段(和公共getter;但所有setter都不管可見性)。 如果需要,可以將此配置(使用版本1.5 )也自動檢測專用字段(有關詳細信息,請參見此處 )。

我猜404與你的HttpMessageConverter無關。 我有同樣的404問題,原因是我忘了只有匹配<url-pattern>請求被發送到DispatcherServlet(我將請求映射從* .do更改為* .json)。 也許這也是你的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM