Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson ignore unknown enum value

Tags:

java

gson

Is there a way to configure gson to ignore an unknown enum value? For example

in my client code there is an enum DeviceType has 2 enum value : PC, MOBILE

But when a server is sent another type for example MAC as another DeviceType. How can I configure my gson deserilalizer to set the DeviceType = null instead of throwing an exception?

Thanks,

Sean

like image 804
Sean Nguyen Avatar asked Oct 11 '22 08:10

Sean Nguyen


2 Answers

Now we can use nullable enum type, for example:

data class SomeDTO (
    val type : DeviceType?,
    //other values
)

In that case, there won't be any exception in parsing.

like image 123
anro Avatar answered Oct 16 '22 15:10

anro


You can easily write a custom JsonDeserializer that ignores unknown values. Read more here. For a starting point, have a look at the source gson source code, class com.google.gson.DefaultTypeAdapters.EnumTypeAdapter

like image 38
E-Riz Avatar answered Oct 16 '22 17:10

E-Riz