且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

spring mvc restcontroller返回json字符串

更新时间:2021-09-25 00:24:37

事实证明,当你使用 @EnableWebMvc 注释,它默认打开一堆http消息转换器。列表中的第二个是 StringHttpMessageConverter ,文档说明将应用于 text / * 内容类型。但是,在使用调试器后,它适用于 * / * 内容类型的String对象 - 显然包括 application / json

It turns out that when you use the @EnableWebMvc annotation that it turns on a bunch of http message converters by default. The second one in the list is the StringHttpMessageConverter which the documentation says will be applied for text/* content types. However, after stepping through with the debugger, it applies to String objects for */* content types- which obviously includes application/json.

MappingJackson2HttpMessageConverter 负责 application / json 内容类型进一步列在此列表中。因此,对于除String之外的Java对象,将调用此对象。这就是它为Object和Array类型工作的原因,但不是String-尽管使用produce属性设置 application / json 内容类型的好建议。尽管该内容类型是触发此转换器所必需的,但String转换器首先抓住了这个作业!

The MappingJackson2HttpMessageConverter which is responsible for application/json content types is further down on this list. So for Java objects other than String, this one gets called. That's why it was working for Object and Array types, but not String- despite the good suggestions of using the produces attribute to set application/json content type. Although that content type is necessary to trigger this converter, the String converter was grabbing the job first!

因为我正在扩展 WebMvcConfigurationSupport 用于其他一些配置的类,我重写了以下方法以将Jackson转换器放在第一位,这样当内容类型为 application / json 时,我将使用这个而不是字符串转换器:

As I was extending the WebMvcConfigurationSupport class for some other configuration, I overrode the following method to put the Jackson converter first so when the content-type is application/json then this one will be used instead of the String converter:

@Override
protected void configureMessageConverters(
        List<HttpMessageConverter<?>> converters) {
    // put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON
    converters.add(new MappingJackson2HttpMessageConverter());
    // and probably needs a string converter too for text/plain content-type strings to be properly handled
    converters.add(new StringHttpMessageConverter());
}

现在当我从curl调用测试方法时,我得到了所需的test输出而不仅仅是 test ,所以期待JSON的角度客户端现在很高兴。

Now when I call the test method from curl I get the desired "test" output instead of just test, so the angular client which is expecting JSON is now happy.