How to save and retrieve a JSON directly in latest version of RealmDB in Android during runtime without model classes Using RealmDB - Kotlin 1.16.0+

I need to store and retrieve a JSON in ReamDB in runtime without creating a RealmObject for that. Also want to check whether the particular JSON object is present in the DB already using a giving field (like “id”). If it exists, then update the object,If not, then save it as new object.

How to do this in latest version of RealmDB 1.16+ Kotlin SDK in Android.

I searched internet but all examples throw “unresolved references” for classes. It seems they are deprecated and removed.

Please help me.

In the past the best way to do this was to store a single field of JSON in the model. We have recently allowed Mixed fields in new applications to store free-form JSON.

See here for a blog post about it: Model unstructured data - More flexibility for our developers | MongoDB

1 Like

Ooh.

@Tyler_Kaye I need Realm-Kotlin alternative for this ::

import android.util.Log
import androidx.lifecycle.ViewModel
import io.realm.DynamicRealm
import io.realm.DynamicRealmObject
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.kotlin.where
import org.json.JSONObject

class RealmDbViewModel : ViewModel() {

    fun saveJsonToRealm(jsonString: String, primaryKeyField: String) {
        // Convert the jsonString to a JSONObject
        val json = JSONObject(jsonString)
        val realm = Realm.getDefaultInstance()
        try {
            val dynamicRealm = DynamicRealm.getInstance(realm.configuration)
            dynamicRealm.executeTransaction { transactionRealm ->
                // Create or update the schema dynamically
                val schema = transactionRealm.schema
                if (!schema.contains("sample")) {
                    schema.create("sample")
                        .addField(primaryKeyField, String::class.java)
                        .setRequired(primaryKeyField, true)
                        .addPrimaryKey(primaryKeyField)
                }
                val sampleSchema = schema.get("sample")
                json.keys().forEach { key ->
                    if (!sampleSchema!!.hasField(key)) {
                        when (json.get(key)) {
                            is Int -> sampleSchema.addField(key, Int::class.java)
                            is Long -> sampleSchema.addField(key, Long::class.java)
                            is Float -> sampleSchema.addField(key, Float::class.java)
                            is Double -> sampleSchema.addField(key, Double::class.java)
                            is Boolean -> sampleSchema.addField(key, Boolean::class.java)
                            is String -> sampleSchema.addField(key, String::class.java)
                            // Add other types as needed
                        }
                    }
                }
                Log.d("TAG", "saveJsonToRealm: ${sampleSchema?.className}")

                // Create and populate the DynamicRealmObject
                val sample = transactionRealm.createObject(sampleSchema?.className, json.getString(primaryKeyField))
                json.remove("id")
                json.keys().forEach { key ->
                    when (val value = json.get(key)) {
                        is Int -> sample.setInt(key, value)
                        is Long -> sample.setLong(key, value)
                        is Float -> sample.setFloat(key, value)
                        is Double -> sample.setDouble(key, value)
                        is Boolean -> sample.setBoolean(key, value)
                        is String -> sample.setString(key, value)
                        // Handle other types if needed
                    }
                }
            }
        } finally {
            realm.close()
        }
    }

    fun testSaveJsonToRealm(onResult: (String) -> Unit) {
        // Sample JSON string
        val jsonString = """
            {
                "id": "3",
                "name": "John Doe",
                "age": 30,
                "isActive": true
            }
        """.trimIndent()
        saveJsonToRealm(jsonString, "id")

        // Query Realm to check if the object is saved
        val realm = Realm.getDefaultInstance()
        try {
            val savedObject = DynamicRealm.getInstance(realm.configuration).where("sample")
                .equalTo("id", "1")
                .findFirst()

            onResult("Saved Object: ${savedObject?.toString()}")
        } finally {
            realm.close()
        }
    }
}