Java Spring 3.0 使用 jackson 消息转换器制作 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2259551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring 3.0 making JSON response using Hymanson message converter
提问by dupdup
i configure my messageconverter as Hymanson's then
我将我的 messageconverter 配置为 Hymanson 的然后
class Foo{int x; int y}
and in controller
并在控制器中
@ResponseBody
public Foo method(){
return new Foo(3,4)
}
from that i m expecting to return a JSON string {x:'3',y:'4'} from server without any other configuration. but getting 404 error response to my ajax request
我希望从服务器返回一个 JSON 字符串 {x:'3',y:'4'} 而没有任何其他配置。但是对我的 ajax 请求得到 404 错误响应
If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters.
如果该方法使用@ResponseBody 进行注释,则返回类型将写入响应 HTTP 正文。返回值将使用 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 ? like adding annotations for class Foo
我错了吗 ?或者我应该使用序列化程序将我的响应对象转换为 Json 字符串,然后将该字符串作为响应返回。(我可以正确地进行字符串响应)还是应该进行一些其他配置?比如为 Foo 类添加注释
here is my conf.xml
这是我的 conf.xml
<bean id="HymansonMessageConverter" class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter">
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="HymansonMessageConverter"/>
</list>
</property>
回答by BalusC
A HTTP 404 error just means that the resource cannot be found. That can have 2 causes:
HTTP 404 错误仅表示无法找到资源。这可能有两个原因:
- Request URL is wrong (client side error or wrong URL in given link/button).
- Resource is not there where you expect it is (server side error).
- 请求 URL 错误(客户端错误或给定链接/按钮中的 URL 错误)。
- 资源不在您期望的位置(服务器端错误)。
To fix 1, ensure you're using or providing the correct request URL (casesensitive!). To fix 2, check the server startup logs for any startup errors and fix them accordingly.
要修复 1,请确保您正在使用或提供正确的请求 URL(区分大小写!)。要修复 2,请检查服务器启动日志中是否有任何启动错误并相应地修复它们。
This all goes beyond the as far posted code and information.
这一切都超出了发布的代码和信息。
回答by StaxMan
This is just a guess, but by default Hymanson only auto-detects public fields (and public getters; but all setters regardless of visibility). It is possible to configure this (with version 1.5) to also auto-detect private fields if that is desired (see herefor details).
这只是一个猜测,但默认情况下,Hymanson 仅自动检测公共字段(和公共 getter;但无论可见性如何,所有 setter)。如果需要,可以配置它(使用版本1.5)以自动检测私有字段(有关详细信息,请参见此处)。
回答by Aleksey Otrubennikov
I guess that 404 is not related to your 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). Maybe this is your case also.
我猜 404 与您的 HttpMessageConverter 无关。我有同样的 404 问题,原因是我忘记了只将匹配<url-pattern>
的请求发送到 DispatcherServlet(我将请求映射从 *.do 更改为 *.json)。也许这也是你的情况。
回答by Boris Brudnoy
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) {
MappingHymansonHttpMessageConverter jsonConverter =
new MappingHymansonHttpMessageConverter();
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: MappingHymansonHttpMessageConverter#write()
does the magic.
请注意,该方法不返回任何内容:MappingHymansonHttpMessageConverter#write()
神奇。
回答by uthark
You need the following:
您需要以下内容:
- Set annotation-driven programming model: put
<mvc:annotation-driven />
inspring.xml
- Place jaskson jar (Maven artifactId is
org.codehaus.Hymanson:Hymanson-mapper-asl
) in classpath. Use as the following:
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public @ResponseBody Foo method(@Valid Request request, BindingResult result){ return new Foo(3,4) }
- 设置注解驱动的编程模型:将
<mvc:annotation-driven />
在spring.xml
- 将 jaskson jar(Maven artifactId is
org.codehaus.Hymanson:Hymanson-mapper-asl
)放在类路径中。 使用如下:
@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
请注意,那
@ResponseBody
is applied to return type, not to the method definition.- You need
@RequestMapping
annotation, so that Spring will detect it.
@ResponseBody
应用于返回类型,而不是方法定义。- 您需要
@RequestMapping
注释,以便 Spring 检测到它。
回答by ricor
I found that I need Hymanson-core-asl.jar too, not only Hymanson-mapper-asl.jar
我发现我也需要 Hymanson-core-asl.jar,而不仅仅是 Hymanson-mapper-asl.jar
回答by Sven Haiges
The MessageConverter interface http://static.springsource.org/spring/docs/3.0.x/javadoc-api/defines a getSupportedMediaTypes() method, which in case of the MappingHymansonMessageCoverter returns application/json
MessageConverter 接口http://static.springsource.org/spring/docs/3.0.x/javadoc-api/定义了一个 getSupportedMediaTypes() 方法,在 MappingHymansonMessageCoverter 的情况下返回 application/json
public MappingHymansonHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
I assume a Accept: application/json request header is missing.
我假设 Accept: application/json 请求标头丢失。
回答by rafael lean ansay
In addition to the answers here..
除了这里的答案..
if you are using jquery on the client side, this worked for me:
如果您在客户端使用 jquery,这对我有用:
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');
}
});