aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/JsonUtils.kt
blob: e9d755fab2a2aadea105c2c1acfe68d206e7efa6 (plain)
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
package at.hannibal2.skyhanni.utils

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import java.io.Reader
import kotlin.reflect.jvm.javaType
import kotlin.reflect.typeOf

inline fun <reified T : Any> Gson.fromJson(string: String): T = this.fromJson(string, typeOf<T>().javaType)

inline fun <reified T : Any> Gson.fromJson(jsonElement: JsonElement): T =
    this.fromJson(jsonElement, typeOf<T>().javaType)

inline fun <reified T : Any> Gson.fromJson(reader: Reader): T = this.fromJson(reader, typeOf<T>().javaType)

fun JsonObject.getBoolean(key: String): Boolean {
    return if (has(key)) {
        try {
            get(key).asBoolean
        } catch (_: Exception) {
            false
        }
    } else {
        false
    }
}

fun JsonObject.getStringOrValue(key: String, alternative: String): String {
    return if (has(key)) {
        try {
            get(key).asString
        } catch (_: Exception) {
            alternative
        }
    } else {
        alternative
    }
}