Simple string as JSON return value in spring rest controller

前端 未结 4 1812
离开以前
离开以前 2020-12-17 16:58

Let\'s take a look at the following simple test controller (Used with Spring 4.0.3):

@RestController
public class Te         


        
相关标签:
4条回答
  • 2020-12-17 17:26

    When you return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.

    0 讨论(0)
  • 2020-12-17 17:29

    You can remove the StringHttpMessageConverter which is registered before the jackson converter, - like mentioned in the comment.

    /**
     * Unregister the default {@link StringHttpMessageConverter} as we want
     * Strings to be handled by the JSON converter.
     *
     * Our MappingJackson2HttpMessageConverter will deal with strings.
     *
     * @param converters
     *            List of already configured converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof StringHttpMessageConverter);
    }
    
    0 讨论(0)
  • 2020-12-17 17:39

    Here are the steps that I did to achieve this :

    1. Add dependency in pom file:

      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.9.3</version>
      </dependency>
      
    2. Put @ResponseBody annotation on your method like this:

      @RequestMapping(value = "/getCountries", method = RequestMethod.GET)    
      @ResponseBody    
      public List<Country> getCountries() {    
          return countryDAO.list();    
      }
      
    0 讨论(0)
  • 2020-12-17 17:42

    If you want to return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.

    @RestController
    public class TestController
    {
       @RequestMapping("/getString")
       public String getString()
      {
        return JSONObject.quote("Hello World");
      }
    }
    
    0 讨论(0)
提交回复
热议问题