春季和序列化json-如何在没有春季靴子的情况下自定义全球杰克逊

发布于 2025-02-09 05:00:06 字数 671 浏览 3 评论 0原文

我使用的是无弹簧靴的干净弹簧MVC框架(v5.3.21)。 我正在与GSON Library合作,该图书馆被Spring用来序列化视图模型,并使用请求方法返回。

 public class Coffee {
    String name = "n";
    String brand = "b";
 }
    
 @RequestMapping(value={"/coffe"}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
 public Coffee getCoffee() {
    return new Coffee();
 }

最近,我在类路径上添加了Jackson(V 2.13.3),并且我注意到序列化的作用差异很大。首先 - 在默认情况下序列化的GSON非私有字段中,现在它们在客户端不可见。 我知道我可以将注释添加

@JsonAutoDetect(fieldVisibility = Visibility.NON_PRIVATE)

到所有模型类中,也可以将字段更改为公众(据我发现,杰克逊的默认可见性是公开的)。 但是我只想在整个配置上更改一次,而没有重写许多

我尝试过很多选项的代码,但是没有弹簧启动,它们都无法使用。 您知道用干净的弹簧更改此默认设置吗?

I'm using clean Spring MVC framework (v5.3.21) without Spring Boot.
I was working with Gson library, which was used by Spring to serialize view models, returned with request methods.

 public class Coffee {
    String name = "n";
    String brand = "b";
 }
    
 @RequestMapping(value={"/coffe"}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
 public Coffee getCoffee() {
    return new Coffee();
 }

Recently I added Jackson (v 2.13.3) on the classpath and I've noticed serialization works much different. First of all - in Gson non-private field where serialized by default, now they are not visible at the client side.
I know I can add annotation

@JsonAutoDetect(fieldVisibility = Visibility.NON_PRIVATE)

to all the model classes, or change fields to public (Jackson default visibility for fields is PUBLIC, as far as I found out).
But I would like to change just once, globally, in configuration, without rewriting code of many

I tried many options, but none of them doesn't work without Spring Boot.
Do you know to change this default setting with clean Spring?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

于我来说 2025-02-16 05:00:06

您可以创建ObjectMapper BEAN,可以是应用程序的全局

public ObjectMapper objectMapper() {

    ObjectMapper mapper  = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.NON_PRIVATE));

    return mapper;
 }

You can create ObjectMapper bean which can be global for application

public ObjectMapper objectMapper() {

    ObjectMapper mapper  = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.NON_PRIVATE));

    return mapper;
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文