spring mvc restcontroller return json string

时间:2015-05-13 03:07:08

标签: json spring-mvc jackson

I have a Spring MVC controller with the following method:

@RequestMapping(value = "/stringtest", method = RequestMethod.GET)
public String simpletest() throws Exception {
    return "test";
}

This sits inside a controller that starts like this:

@RestController
@RequestMapping(value = "/root")
public class RootController

When I call other methods that return objects, those objects are serialized by Jackson into JSON. But this method which returns a String is not converted to JSON. In case it's not clear, here's an example using curl:

$curl http://localhost:8080/clapi/root/stringtest 
test

So the problem is that "test" without any quotes is not a JSON string, but my REST client is expecting a string. I expected the curl command to show that string with quotes around it so it's legal JSON instead:

"test"

I am using Spring WebMVC 4.1.3 and Jackson 2.4.3. I have tried adding a "produces" attribute to the RequestMapping to say it should return JSON. In this case, the Content-Type attribute sent back is "application/json" but still the test string is not quoted.

I could workaround this by calling a JSON library to convert by Java String to JSON, but it seems like Spring MVC and Jackson generally do this automatically. Yet somehow they are not doing it in my case. Any ideas what I might have configured wrong to be getting just test back instead of "test"?

3 个答案:

答案 0 :(得分:8)

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

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

当我为其他配置扩展WebMvcConfigurationSupport类时,我覆盖了以下方法以将Jackson转换器放在第一位,因此当内容类型为application/json时,将使用此方法而不是字符串转换器:

@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的角度客户端现在很高兴。

答案 1 :(得分:1)

试试这个:

@RequestMapping(value = "/stringtest", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)

答案 2 :(得分:0)

尝试这样的事情

@RequestMapping(value = "/stringtest", method = RequestMethod.GET, produces="application/json")
public @ResponseBody String simpletest() throws Exception {
    return "test";
}