Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a Kotlin data class property/field from serialization/deserialization using gson

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?

like image 998
idrisadetunmbi Avatar asked Nov 22 '18 07:11

idrisadetunmbi


People also ask

How to exclude fields in Gson?

ExclusionStrategy strategy = new ExclusionStrategy() { @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } @Override public boolean shouldSkipField(FieldAttributes field) { return field. getAnnotation(Exclude. class) !=

How would you exclude a field of a class from serialization?

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.

Does Gson ignore extra fields?

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.

What is the use of @expose in Gson?

@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.


3 Answers

@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.

like image 58
Quan Lam Avatar answered Oct 19 '22 03:10

Quan Lam


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.

like image 2
IustoFulmine Avatar answered Oct 19 '22 01:10

IustoFulmine


data class Foo (
    @Expose(deserialize = false) val bar: Bar
)
like image 1
Sergei Rybalkin Avatar answered Oct 19 '22 02:10

Sergei Rybalkin