enum class mapping issue when enum not found

Viewed 900

I have a class in kotlin which is an enum class as below

enum class Status {
  @SerializedName("open")
  OPEN,
  @SerializedName("close")
  CLOSE,
  UNKNOWN
}

I have another class called ticket using the status enum class

class Order(
    var id: String,
    var status: Status = Status.UNKNOWN,
}

When the GSON map the value received, I have an exception because the status field now contains a new value in_progress. As this state is not declared in the Status class, the exception happened.

How can I avoid the exception to make sure that if a new status is set in the GSON but not defined in the Status class, I got status UNKNOWN?

Any idea on how to return a default value UNKNOWN in my case when nothing match ?

Thanks

1 Answers

If you want to go down this road then your problem is the enum. GSON is waiting for an enum value so if in_progress isn't a value GSON will say no.

What you can do is creating a new datatyp and wrap your enum in it, but the generell Idea for using a enum is lost.

A different approach is to get rid of the enum completely. Implementing an interface called status and implement a class for every type of Status. This is kinda a enum+. You can than send your Order with something like Var Status : OrderStatus = In_Progress() Var Status: OrderStatus = Unkonwn() Later you can call something like instanceof to get the type of OrderStatus checked.

After your edit: You must say GSON exactly what you are waiting for (see GSON Adapters) if you want the behaviour from your description you should look for an other way to communicate.

Related