Google-GSON的Spring MVC映射视图? [英] Spring MVC mapping view for Google-GSON?

查看:135
本文介绍了Google-GSON的Spring MVC映射视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否有 Gson 的Spring MVC映射视图?我正在寻找类似于 org.springframework.web.servlet.view.json.MappingJacksonJsonView



理想情况下,需要使用我的ModelMap并将其呈现为JSON,并尊重在ContentNegotiatingViewResolver声明中设置的renderedAttributes。



我们计划在应用程序中广泛使用Gson,因为它似乎比Jackson更安全和更好。也就是说,为了实现本机JSON视图,我们需要拥有两个不同的JSON库,因此我们已经陷入困境。



预先感谢!

[交叉发布到 Spring论坛]

解决方案

aweigold让我获得了大部分的方式,但具体地提出了Spring 3.1 Java这是我做的。



抓斗 GsonHttpMessageConverter.java 项目。



注册您的 GsonHttpMessageConverter 与MVC配置中的消息转换器。

  @EnableWebMvc 
公共类WebConfig扩展WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(Li ST< HttpMessageConverter<?>>转换器){
转换器.add(新的GsonHttpMessageConverter());


$ / code>

Spring文档概述了这个过程,但不是晶莹剔透。为了使它正常工作,我必须扩展 WebMvcConfigurerAdapter ,然后重载 configureMesageConverters 。这样做后,你应该可以在你的控制器方法中执行以下操作:

  @Controller 
public class AppController {
@RequestMapping(value =messages,产生= MediaType.APPLICATION_JSON_VALUE)
public List< Message> getMessages(){
// ..获取消息列表
返回消息;
}
}

瞧! JSON输出。


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.

Ideally it would take my ModelMap and render it as JSON, respecting my renderedAttributes set in the ContentNegotiatingViewResolver declaration

We plan to use Gson extensively in the application as it seems safer and better than Jackson. That said, we're getting hung up by the need to have two different JSON libraries in order to do native JSON views.

Thanks in advance!

[cross-posted to Spring forums]

解决方案

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<HttpMessageConverter<?>> 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<Message> getMessages() {
    // .. Get list of messages
    return messages;
  }
}

And voila! JSON output.

这篇关于Google-GSON的Spring MVC映射视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆