package com.blaze.rtnblazesdk.utils.parsing import android.util.Log import com.facebook.react.bridge.ReadableMap import com.google.gson.Gson import com.google.gson.GsonBuilder private const val TAG = "GsonUtils" /** * Extension function to convert a ReadableMap to a object of type T * using a custom Gson instance with registered custom adapters. * * @return An instance of type T deserialized from the ReadableMap, or null if deserialization fails. */ internal inline fun ReadableMap.toObject(): T? { return try { // Convert ReadableMap to JSON string val jsonString = this.toJsonString() // Deserialize JSON string to data class of type T jsonString.fromJsonString() } catch (e: Exception) { Log.e(TAG, "toDataClass: $e") null } } /** * Creates a GsonBuilder with registered custom type adapters. * * @return A GsonBuilder instance with custom type adapters registered. */ private fun createCustomGsonBuilder(): GsonBuilder = GsonBuilder() .registerRoundingIntAdapterFactory() .registerBlazeEnumMapperAdapterFactory() /** * Creates a customized Gson instance. * * @return A Gson instance with custom type adapters registered. */ private fun createCustomGson(): Gson { return createCustomGsonBuilder().setPrettyPrinting().create() } /** * Extension function to convert a ReadableMap to a JSON string. * * @return The JSON string representation of the ReadableMap. */ internal fun ReadableMap.toJsonString(): String { val map = this.toHashMap() return createCustomGson().toJson(map) } /** * Generic extension function to deserialize a JSON string into a data class of type T * using a custom Gson instance with registered custom adapters. * * @return An instance of type T deserialized from the JSON string, or null if deserialization fails. */ internal inline fun String.fromJsonString(): T? { return try { createCustomGson() .fromJson(this, T::class.java) } catch (e: Exception) { Log.e(TAG, "fromJsonString: $e") null } } /** * Generic extension function to serialize any data class to a JSON string using Gson * with registered custom adapters. * * @return The JSON string representation of the data class, or null if serialization fails. */ internal fun Any.toJsonString(): String? { return try { createCustomGson().toJson(this) } catch (e: Exception) { null } } /** * Extension function to deserialize any object assumed to be representable as a JSON string into a data class of type T. * Requires that the Any object can be transformed into a JSON string representation directly or indirectly. * * @return An instance of type T deserialized from the JSON representation of the object, or null if deserialization fails. */ internal inline fun Any.toObject(): T? { return try { val jsonString = when (this) { is String -> this else -> this.toJsonString() // This calls toJsonString if available } createCustomGson().fromJson(jsonString, T::class.java) } catch (e: Exception) { Log.e(TAG, "Error deserializing object to type ${T::class.java}: $e") null } }