Home > Net >  Cloud function sending json as map
Cloud function sending json as map

Time:11-30

I am sending json to cloud function via postman and it works fine, how can I send same json as map to cloud function:

Sending via postman:

{
    "data": {
        "users": [
            {
                "phone": "55512345"
            },
            {
                "phone": "972525276676"
            },
            {
                "phone": "55512347"
            }
        ]
    }
}

Sending via android:

 private fun addMessage(): Task<String>? {
        val usr1 = User("55512345")
        val usr2 = User("972525276676")
        val usr3 = User("55512347")
        val userList = listOf(usr1,usr2,usr3)

        val data: MutableMap<String, Any> = HashMap()
        data["users"] = userList

        functions.getHttpsCallable("getUsers")
            .call(data)
            .addOnFailureListener {
                Log.d("DTAG", it.toString())
            }
            .addOnSuccessListener {
                Log.d("DTAG","Ok: ${it.data.toString()}")
            }
        return null
    }

Where user is:

 data class User(var phone:String)

Cloud function:

exports.getUsers = functions.https.onRequest(async (request, response) => {
    const data = request.body.data;
    if (data !== null && data.users !== null) {
    const users = data.users;
    const phonelist = users.map(user => user.phone.toString());
    const userlist = []

    const snapshot = await db.collection("users").get()
    snapshot.docs.forEach((userDoc) => {
        const phone = userDoc.get("phone")
        if(phone === null) return;
        const isContain = phonelist.reduce((acc, num) => acc || phone.includes(num), false)
        if(isContain) {
            userlist.push(userDoc.data())
        }
    })
    response.status(200).json({result: userlist})
    }     else{
       response.sendStatus(403)
    }
});

Error:

Object cannot be encoded in JSON: User(phone=55512345)

CodePudding user response:

The error is telling you that the client SDK doesn't know what to do with the User class. You'll have to build a Map<String, Object> out of the data.

val userMap1 = mapOf("phone" to "55512345")
...
val userList = listOf(userMap1, ...)

  • Related