-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGson.kt
43 lines (36 loc) · 1.26 KB
/
Gson.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.paypal.messages.extensions
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import kotlin.reflect.KClass
fun KClass<Gson>.jsonElementToMutableMap(jsonElement: JsonElement): MutableMap<String, Any> {
val mutableMap = mutableMapOf<String, Any>()
if (jsonElement.isJsonObject) {
val jsonObject = jsonElement.asJsonObject
for ((key, value) in jsonObject.entrySet()) {
mutableMap[key] = jsonValueToAny(value)
}
}
return mutableMap
}
fun KClass<Gson>.jsonValueToAny(jsonElement: JsonElement): Any {
return when {
jsonElement.isJsonPrimitive -> {
val primitive = jsonElement.asJsonPrimitive
when {
primitive.isBoolean -> primitive.asBoolean
primitive.isNumber -> primitive.asNumber
else -> primitive.asString
}
}
jsonElement.isJsonArray -> jsonElement.asJsonArray
jsonElement.isJsonObject -> jsonElementToMutableMap(jsonElement)
else -> throw IllegalArgumentException("Unsupported JSON element type: ${jsonElement::class.java.simpleName}")
}
}
fun Gson.getJsonObject(value: Any): JsonObject {
return this.fromJson(this.toJson(value), JsonObject::class.java)
}
fun Gson.getJsonElement(value: Any): JsonElement {
return this.fromJson(this.toJson(value), JsonElement::class.java)
}