Home > database >  How to reuse a custom object serializer for a list of objects?
How to reuse a custom object serializer for a list of objects?

Time:01-26

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?

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?

CodePudding user response:

Do I need to write a new Serializer for the Type List or can I reuse StudentSerializer

You can reuse the StudentSerializer serializer already defined: in your case you can annotate your studentsfield 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:

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