json - Spring Boot 中同一实体的多个自定义序列化程序

标签 json serialization spring-boot jackson json-serialization

我正在开发 Spring Boot 应用程序。我为一个实体 A 创建了一个自定义序列化程序,并使用 @JsonSerialize(using = CustomSerializer.class) 注释注册了它。每当我在 ResponseEntity<> 中发送 A 时,自定义序列化器就会被调用,直到此时一切正常。

现在有另一个 API,我需要在其中发送 A 的集合作为响应。但是我不能使用相同的序列化程序来构造 A 的列表,因为响应参数完全不同。我需要为同一个实体再写一个序列化器。

如何为同一实体配置 2 个序列化程序?它们应该根据响应中发送的对象类型来调用,即当我发送 A 时,应该调用 serializer1,当我发送 Collection 时,应该调用 serializer2。 请帮忙!

最佳答案

一个简单的解决方法是注释集合以对内容使用特定的序列化程序。例如

@JsonSerialize(using = CustomSerializer.class)
class A {
}

class AList {
    @JsonSerialize(contentUsing = AnotherCustomSerializer.class)
    private final List<A> list;
}

关于json - Spring Boot 中同一实体的多个自定义序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569640/

相关文章:

java - 从 postman (休息服务)如何将 json 日期(字符串格式)发送到接受日期对象的 java

java - JSONTypeInfo 不忽略继承映射中的属性

java - Spring Azure AD - 身份验证后获取用户的地址

spring - Spring Boot 和 Spring IO 是什么关系?

java - org.springframework.web.HttpRequestMethodNotSupportedException : Request method 'POST' is not supported

php - 在 FullCalendar 4 中显示我的数据库中的事件

java - 错误 : 'ContentNegotiatingViewResolver' of Spring 3. 0.3 MVC Portlet+JSON

json - Apache Airflow : airflow initdb results in "ImportError: No module named json"

.net - 将数据保存在简单的 .NET Windows 应用程序中的什么位置?

java - 在Java中将类重构为接口(interface)时如何支持向后兼容的序列化?