Spring MVC mapping view for Google-GSON?

后端 未结 2 1977
孤城傲影
孤城傲影 2021-01-31 21:46

Does anyone know if there is a Spring MVC mapping view for Gson? I\'m looking for something similar to org.springframework.web.servlet.view.json.MappingJacksonJsonView.

2条回答
  •  遇见更好的自我
    2021-01-31 21:54

    aweigold got me most of the way there, but to concretely outline a solution for Spring 3.1 Java based configuration, here's what I did.

    Grab GsonHttpMessageConverter.java from the spring-android-rest-template project.

    Register your GsonHttpMessageConverter with the message converters in your MVC config.

    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
      @Override
      public void configureMessageConverters(List> converters) {
        converters.add(new GsonHttpMessageConverter());
      }
    }
    

    The Spring docs outline this process, but aren't crystal clear. In order to get this to work properly, I had to extend WebMvcConfigurerAdapter, and then override configureMesageConverters. After doing this, you should be able to do the following in your controller method:

    @Controller
    public class AppController {
      @RequestMapping(value = "messages", produces = MediaType.APPLICATION_JSON_VALUE)
      public List getMessages() {
        // .. Get list of messages
        return messages;
      }
    }
    

    And voila! JSON output.

提交回复
热议问题