gpt4 book ai didi

json - Google-GSON 的 Spring MVC 映射 View ?

转载 作者:IT老高 更新时间:2023-10-28 13:57:01 27 4
gpt4 key购买 nike

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

理想情况下,它将采用我的 ModelMap 并将其呈现为 JSON,尊重我在 ContentNegotiatingViewResolver 声明中设置的 renderAttributes

我们计划在应用程序中广泛使用 Gson,因为它看起来比 Jackson 更安全、更好。也就是说,我们需要拥有两个不同的 JSON 库才能执行原生 JSON View 。

提前致谢!

[交叉发布到 Spring forums ]

最佳答案

aweigold 帮助我完成了大部分工作,但要具体概述基于 Spring 3.1 Java 的配置的解决方案,这就是我所做的。

捕获 GsonHttpMessageConverter.java来自 spring-android-rest-template项目。

使用 MVC 配置中的消息转换器注册您的 GsonHttpMessageConverter

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

Spring 文档概述了这个过程,但并不十分清楚。为了让它正常工作,我必须扩展 WebMvcConfigurerAdapter,然后重写 configureMesageConverters。完成此操作后,您应该能够在 Controller 方法中执行以下操作:

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

瞧! JSON 输出。

关于json - Google-GSON 的 Spring MVC 映射 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754055/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com