Spring Boot-自定义JSON序列化 [英] Spring Boot - Custom JSON Serialization

查看:747
本文介绍了Spring Boot-自定义JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Jackson库时,我通常使用mixins来执行自定义序列化和反序列化.我在Spring Boot应用程序中的RestController具有与以下所列类似的方法.我猜Spring Boot使用Jackson将VerifyAccountResponse序列化为字符串.但是,当它们转换为字符串时,这会将我的日历/日期对象转换为长值.我可以通过使用自定义序列化程序将它们转换为适当的格式.但是,我必须在序列化后将返回类型更改为对象.有没有一种方法可以保留相同的签名,并将自定义序列化器添加到Spring Boot执行的默认序列化中.

I generally use mixins to perform custom serialization and deserialization when using Jackson Library. My RestController in Spring Boot app has methods similar to one listed below. I guess Spring Boot uses Jackson to serialize the VerifyAccountResponse into string. However this converts my calendar / date objects into a long value when they are converted to String. I am able to convert them into appropriate format by using custom serializer. However I am having to change the return type into an object after serialization. Is there a way to retain the same signature and add custom serializer to default serialization performed by Spring Boot.

@RequestMapping(value ="verifyAccount", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<VerifyAccountResponse> verifyAccount(@RequestBody VerifyAccountRequest request) {

    VerifyAccountResponse response = service.verifyAccount(request);

    return new ResponseEntity<VerifyAccountResponse>(response, HttpStatus.OK);
}

Updated the below based on the answers , but mixin doesn't seem to take effect -

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    builder.mixIn(ConnectStatus.class, com.datacast.service.util.DateFormatSerializerMixin.class);

    return builder;
}

我创建了一个简单的spring boot项目来对其进行测试,并且效果很好.但是,当我在较大的项目中使用此方法时,日期转换不会发生.有什么可以替代Jackson2ObjectMapperBuilder的吗?

I created a simple spring boot project to test this out and this works fine. But when I use this approach in my larger project , the date conversion is not happening. Could there be anything overriding Jackson2ObjectMapperBuilder ?

推荐答案

您可以通过多种方式在Spring Boot应用程序中自定义Jackson序列化程序.请考虑查看Spring Boot参考指南中有关jackson的文档:

You can customize the Jackson serializer in a spring boot application in a lot of ways. Please consider checking the documentation regarding jackson in the spring boot reference guide:

您可以使用 Jackson2ObjectMapperBuilder 配置自定义序列化程序.

You can configure a custom serializer by using Jackson2ObjectMapperBuilder.

查看全文

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