package io.scanbot.sdk.reactnative.extensions import com.facebook.react.bridge.WritableArray import com.facebook.react.bridge.WritableMap import com.facebook.react.bridge.WritableNativeArray import com.facebook.react.bridge.WritableNativeMap import org.json.JSONArray import org.json.JSONException import org.json.JSONObject @Throws(JSONException::class) fun JSONObject.toWritableMap(): WritableMap { val map = WritableNativeMap() val iterator = this.keys() while (iterator.hasNext()) { val key = iterator.next() when (val value = this.get(key)) { is JSONObject -> { map.putMap(key, value.toWritableMap()) } is JSONArray -> { map.putArray(key, value.toWritableArray()) } is Boolean -> { map.putBoolean(key, value) } is Int -> { map.putInt(key, value) } is Long -> { // WritableMap doesn't support Long for now, and for TS layer it doesn't matter if // it's Long or Double. map.putDouble(key, value.toDouble()) } is Double -> { map.putDouble(key, value) } is Float -> { map.putDouble(key, value.toDouble()) } is String -> { map.putString(key, value) } else -> { map.putNull(key) } } } return map } @Throws(JSONException::class) fun JSONArray.toWritableArray(): WritableArray { val array = WritableNativeArray() for (i in 0 until this.length()) { when (val value = this.get(i)) { is JSONObject -> { array.pushMap(value.toWritableMap()) } is JSONArray -> { array.pushArray(value.toWritableArray()) } is Boolean -> { array.pushBoolean(value) } is Int -> { array.pushInt(value) } is Long -> { array.pushInt(value.toInt()) } is Double -> { array.pushDouble(value) } is Float -> { array.pushDouble(value.toDouble()) } is String -> { array.pushString(value) } else -> { array.pushNull() } } } return array }