I am trying to exclude a Kotlin property from deserialization using gson. I have tried different methods from annotating the property with @Transient
to creating a custom annotation strategy (specifying the strategy in the gson builder of course), but nothing seems to be working, as the property keeps getting null instead of the value I initialized the property with.
I have not tried using the @Expose
annotation, but I do not want to annotate other fields with @Expose
Please, how can I achieve this please using gson + Kotlin?
ExclusionStrategy strategy = new ExclusionStrategy() { @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } @Override public boolean shouldSkipField(FieldAttributes field) { return field. getAnnotation(Exclude. class) !=
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
@SerializeName is used to set the key that json object will include ,however @Expose is used to decide whether the variable will be exposed for Serialisation and Deserialisation ,or not.
@Transient worked for me.
@Transient lateinit var bar: SomeCustomType
Per @Transient definition:
Marks the JVM backing field of the annotated property as
transient
, meaning that it is not part of the default serialized form of the object.
I have yet to find a more elegant solution, but for now, I've given the property a different name and removed it from the class's default constructor.
{
"fName": "Bilbo"
"lName": "Baggins"
}
data class Person(val fName: String) {
lateinit var lNameObj: String
}
Then I can assign lNameObj
in my custom deserializer.
data class Foo (
@Expose(deserialize = false) val bar: Bar
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With