You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复用自定义对象序列化器处理对象列表?

无需为List编写新序列化器,直接复用StudentSerializer即可

你完全不需要专门为List<Student>类型编写新的序列化器,Jackson框架会自动复用你已经实现的StudentSerializer来处理列表中的每一个Student对象。

具体复用方式分两种情况:

1. 局部绑定:给Student类添加注解

直接在Student类上通过@JsonSerialize注解指定使用你的自定义序列化器,这样无论序列化单个Student还是Student列表,都会自动应用该序列化逻辑:

@JsonSerialize(using = StudentSerializer::class)
class Student(
    var id: Long? = null,
    var name: String? = null,
    var courses: MutableList<Course> = mutableListOf()
)

(注:你原代码里的Courses应为笔误,已修正为Course)

2. 全局注册:在ObjectMapper中配置序列化器

如果不想给实体类加注解,可以在初始化ObjectMapper时全局注册StudentSerializer,这样整个应用中所有Student类型的序列化都会使用这个自定义逻辑:

val objectMapper = ObjectMapper().apply {
    val module = SimpleModule()
    module.addSerializer(Student::class.java, StudentSerializer())
    registerModule(module)
}

额外提醒

因为你的Student和Course类存在互相引用(Student有courses列表,Course有students列表),序列化时容易出现循环引用栈溢出的问题,建议添加相关注解处理:

  • 比如在Student的courses字段或Course的students字段上添加@JsonIgnore,忽略反向引用;
  • 或者使用@JsonManagedReference和@JsonBackReference来建立双向引用的序列化规则。

内容的提问来源于stack exchange,提问作者WhiteCherry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:05:21