Skip to content

Commit 600e03c

Browse files
committed
Add enum ordinal json adapter for gson serialization
1 parent 451427d commit 600e03c

File tree

1 file changed

+41
-2
lines changed
  • base/src/main/java/com/enginebai/base/extensions

1 file changed

+41
-2
lines changed

base/src/main/java/com/enginebai/base/extensions/EnumExt.kt

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ import java.lang.reflect.Type
1212
*
1313
* Example:
1414
* enum class MediaType {
15-
* @SerializedName("image-jpeg")
15+
* @SerializedName("jpeg")
1616
* IMAGE_JPG,
17-
* @SerializedName("video-mp4")
17+
* @SerializedName("mp4")
1818
* VIDEO_MP4
1919
* }
2020
*
@@ -86,4 +86,43 @@ class EnumHasValueJsonAdapter<T> : JsonSerializer<T>, JsonDeserializer<T> where
8686
return parsedValue
8787
}
8888

89+
}
90+
91+
/**
92+
* Serialize or deserialize the enum by ordinal.
93+
*
94+
* Suppose we have a field representing order status:
95+
* 0: reservation success, 1: arrival, 2: cancel
96+
*
97+
* We define a enum for this field and we can use json adapter:
98+
*
99+
* @JsonAdapter(EnumOrdinalJsonAdapter::class)
100+
* enum class OrderStatus {
101+
* RESERVATION_SUCCESS,
102+
* ARRIVAL,
103+
* CANCEL
104+
* }
105+
*
106+
* data class Order(
107+
* val status: OrderStatus?
108+
* )
109+
*/
110+
class EnumOrdinalJsonAdapter<T> : JsonSerializer<T>, JsonDeserializer<T> where T : Enum<T> {
111+
override fun serialize(
112+
src: T,
113+
typeOfSrc: Type?,
114+
context: JsonSerializationContext?
115+
): JsonElement {
116+
return JsonPrimitive(src.ordinal)
117+
}
118+
119+
override fun deserialize(
120+
json: JsonElement,
121+
typeOfT: Type?,
122+
context: JsonDeserializationContext?
123+
): T? {
124+
val parsedValue = (typeOfT as Class<T>).enumConstants?.associateBy { it.ordinal }?.get(json.asInt)
125+
parsedValue ?: kotlin.run { Timber.w("Can not deserialize value ${json.asString} to $typeOfT") }
126+
return parsedValue
127+
}
89128
}

0 commit comments

Comments
 (0)