简体   繁体   English

Spring 3.0使用jackson消息转换器进行JSON响应

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

i configure my messageconverter as Jackson's then 我将我的messageconverter配置为杰克逊的

class Foo{int x; int y}

and in controller 并在控制器中

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

from that im expecting to return a JSON string {x:'3',y:'4'} from server without any other configuration. 从那个我期望从服务器返回一个JSON字符串{x:'3',y:'4'},没有任何其他配置。 but getting 404 error response to my ajax request 但得到我的ajax请求的404错误响应

If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. 如果使用@ResponseBody注释该方法,则将返回类型写入响应HTTP正文。 The return value will be converted to the declared method argument type using HttpMessageConverters. 返回值将使用HttpMessageConverters转换为声明的方法参数类型。

Am I wrong ? 我错了吗 ? or should I convert my response Object to Json string myself using serializer and then returning that string as response.(I could make string responses correctly) or should I make some other configurations ? 或者我应该使用序列化程序将我的响应对象转换为Json字符串,然后将该字符串作为响应返回。(我可以正确地进行字符串响应)或者我应该进行其他配置吗? like adding annotations for class Foo 比如为Foo类添加注释

here is my conf.xml 这是我的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>

You need the following: 您需要以下内容:

  1. Set annotation-driven programming model: put <mvc:annotation-driven /> in spring.xml 设置注释驱动的编程模型:在spring.xmlspring.xml <mvc:annotation-driven />
  2. Place jaskson jar (Maven artifactId is org.codehaus.jackson:jackson-mapper-asl ) in classpath. 在类路径中放置jaskson jar(Maven artifactId是org.codehaus.jackson:jackson-mapper-asl )。
  3. Use as the following: 使用如下:

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

This works for me. 这适合我。

Please note, that 请注意,那

  1. @ResponseBody is applied to return type, not to the method definition. @ResponseBody应用于返回类型,而不是方法定义。
  2. You need @RequestMapping annotation, so that Spring will detect it. 你需要@RequestMapping注释,以便Spring检测它。

This worked for me: 这对我有用:

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

Note that the method doesn't return anything: MappingJacksonHttpMessageConverter#write() does the magic. 请注意,该方法不返回任何内容: MappingJacksonHttpMessageConverter#write()完成了魔术。

The MessageConverter interface http://static.springsource.org/spring/docs/3.0.x/javadoc-api/ defines a getSupportedMediaTypes() method, which in case of the MappingJacksonMessageCoverter returns application/json 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));
}

I assume a Accept: application/json request header is missing. 我假设缺少一个Accept:application / json请求标头。

A HTTP 404 error just means that the resource cannot be found. HTTP 404错误仅表示无法找到资源。 That can have 2 causes: 这可能有两个原因:

  1. Request URL is wrong (client side error or wrong URL in given link/button). 请求URL错误(客户端错误或给定链接/按钮中的错误URL)。
  2. Resource is not there where you expect it is (server side error). 资源不在您期望的位置(服务器端错误)。

To fix 1, ensure you're using or providing the correct request URL (casesensitive!). 要修复1,请确保您正在使用或提供正确的请求URL(区分大小写!)。 To fix 2, check the server startup logs for any startup errors and fix them accordingly. 要修复2,请检查服务器启动日志以查找任何启动错误并相应地进行修复。

This all goes beyond the as far posted code and information. 这一切都超出了迄今为止发布的代码和信息。

我发现我也需要jackson-core-asl.jar,而不仅仅是jackson-mapper-asl.jar

In addition to the answers here.. 除了这里的答案..

if you are using jquery on the client side, this worked for me: 如果你在客户端使用jquery,这对我有用:

Java: Java的:

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

Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function): 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');
    }
});

This is just a guess, but by default Jackson only auto-detects public fields (and public getters; but all setters regardless of visibility). 这只是一个猜测,但默认情况下,杰克逊只会自动检测公共字段(和公共getter;但所有setter都不管可见性)。 It is possible to configure this (with version 1.5 ) to also auto-detect private fields if that is desired (see here for details). 如果需要,可以将此配置(使用版本1.5 )也自动检测专用字段(有关详细信息,请参见此处 )。

I guess that 404 is not related to your HttpMessageConverter. 我猜404与你的HttpMessageConverter无关。 I had same 404-issue and the reason was that I forgot that only requests matching <url-pattern> are sent to DispatcherServlet (I changed request mapping from *.do to *.json). 我有同样的404问题,原因是我忘了只有匹配<url-pattern>请求被发送到DispatcherServlet(我将请求映射从* .do更改为* .json)。 Maybe this is your case also. 也许这也是你的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM