
com.amplitude.core.utilities.JSON.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of analytics-core Show documentation
Show all versions of analytics-core Show documentation
Amplitude Kotlin Core library
The newest version!
package com.amplitude.core.utilities
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
internal fun Map<*, *>?.toJSONObject(): JSONObject? {
if (this == null) {
return null
}
val jsonObject = JSONObject()
for (entry in entries) {
val key = entry.key as? String ?: continue
val value = entry.value.toJSON()
jsonObject.put(key, value)
}
return jsonObject
}
internal fun JSONObject.toMapObj(): Map {
val map = mutableMapOf()
for (key in this.keys()) {
map[key] = this[key].fromJSON()
}
return map
}
internal fun JSONArray.toListObj(): List {
val list = mutableListOf()
for (i in 0 until this.length()) {
val value = this[i].fromJSON()
list.add(value)
}
return list
}
internal fun Collection<*>?.toJSONArray(): JSONArray? {
if (this == null) {
return null
}
val jsonArray = JSONArray()
for (element in this) {
jsonArray.put(element.toJSON())
}
return jsonArray
}
internal fun Array<*>?.toJSONArray(): JSONArray? {
if (this == null) {
return null
}
val jsonArray = JSONArray()
for (element in this) {
jsonArray.put(element.toJSON())
}
return jsonArray
}
private fun Any?.fromJSON(): Any? {
return when (this) {
is JSONObject -> this.toMapObj()
is JSONArray -> this.toListObj()
// org.json uses BigDecimal for doubles and floats; normalize to double
// to make testing for equality easier.
is BigDecimal -> this.toDouble()
JSONObject.NULL -> null
else -> this
}
}
private fun Any?.toJSON(): Any? {
return when (this) {
is Map<*, *> -> this.toJSONObject()
is Collection<*> -> this.toJSONArray()
is Array<*> -> this.toJSONArray()
else -> this
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy