Android Convert Firebase Cloud Function Reponse (HttpsCallableResult) to Json or Class Object/POJO

October 11, 2019

NOTE:

  • Using org.json.JSONObject to convert Map to json string
  • Using Kotlin Serialization to convert json string to class object/pojo
  • I believe Gson could be used to achieve the above as well
@Serializable
class Person(val name: String, @SerialName("nick_name") val nickName: String, val age: Int, val friends: List<String>)
fun getPersonFunction(): Task<Person> {
    val functions = FirebaseFunctions.getInstance()

    val data = mapOf(
        "name" to "Desmond"
    )

    return functions.getHttpsCallable("get_person")
        .call(data)
        .continueWith { task ->
            @Suppress("UNCHECKED_CAST")
            val result = task.result?.data as Map<String, Any>

            // convert data to json string
            val jsonString = JSONObject(result).toString()

            // convert Json string to Person
            val json = Json(JsonConfiguration.Stable.copy(strictMode = false))
            json.parse(Person.serializer(), jsonString)
        }
}

NOTE: Refer Android Call Cloud Functions for Firebase

NOTE: Refer Create Compatible Cloud Functions for Firebase With Python

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.