Hey, I have a question related to data classes and...
# announcements
f
Hey, I have a question related to data classes and Jackson deserialization. Let's suppose I have a
data class
as the class to be deserialized and I need to transform a JSON value into a custom object. For instance, a
String
value from JSON gets transformed into an
enum
value in my app, or color
String
into an
Int
. In Java, what I did was doing the transformation in the setter of the field. In Kotlin, it seems like Jackson uses the generated constructor for deserializing instead of getters and setters, so I end up having a
InvalidFormatException
because it cannot construct an instance of T type from some R type. BTW, I'm using
KotlinModule
in my
ObjectParser
Is there an elegant solution to this? Or this is not a good use case for data classes? A not so elegant solution I found was defining in my constructor a
var
of my "transformed" type and then a function
set<jsonFieldName>
that Jackson uses because it JSON field name and constructor field name don't match
j
You can add secondary constructor and use @JsonCreator
👍 1
Something like @JsonCreator constructor(val: Int) this(val.toString())
❤️ 1
f
Thanks for your answer! It worked