简体   繁体   English

如何为对象列表重用自定义 object 序列化程序?

[英]How to reuse a custom object serializer for a list of objects?

I've written a custom "student" serializer and want to reused it for a list of student.我已经编写了一个自定义的“学生”序列化程序,并希望将其重新用于学生列表。 Do I need to write a new Serializer for the Type List<Student> or can I reuse StudentSerializer ?我是否需要为 Type List<Student>编写一个新的 Serializer 或者我可以重用StudentSerializer吗?

For example:例如:

class Student(
var id: Long? = null,
var name: String? = null,
var courses: MutableList<Courses> = mutableListOf()
)
class Course(
var id: Long? = null,
var name: String? = null,
var students: MutableList<Student> = mutableListOf()
)
class StudentSerializer : JsonSerializer<Student>() {

    override fun serialize(student: Student?, gen: JsonGenerator, serializers: SerializerProvider?) {
     gen.writeStartObject()
     // ...
     gen.writeEndObject()
    }
 }

How can I reuse this Serializer for this scenario?我如何在这种情况下重用这个 Serializer?

Do I need to write a new Serializer for the Type List or can I reuse StudentSerializer我是否需要为类型列表编写一个新的序列化程序,或者我可以重用 StudentSerializer

You can reuse the StudentSerializer serializer already defined: in your case you can annotate your students field in the Course class with the JsonSerialize annotation with contentUsing directive where contentusing indicates the serializer class to use for serializing contents (elements of a Collection/array, values of Maps) of one annotated property:您可以重用已经定义的StudentSerializer序列化程序:在您的情况下,您可以使用带有contentUsing指令的JsonSerialize注释在Course class 中注释您的students字段,其中contentusing指示序列化程序 class 用于序列化内容(集合/数组的元素,值一个注释属性的地图):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM