Use custom JSON serializers with firebase

前端 未结 2 1649
醉梦人生
醉梦人生 2021-01-13 03:43

Is it possible to get JsonObjects or strings in Json format when using DataSnapshot.getValue()? Maybe I wasn\'t thorough enough with my search, but I couldn\'t find a way to

2条回答
  •  爱一瞬间的悲伤
    2021-01-13 04:13

    Based on @RominaV answer and in case it may be helpful to someone that's what I have in Kotlin:

     myRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
    
                adapter.clear()
    
                dataSnapshot.children.forEach {
    
                    val cardMap = it.value
                    val json = Gson().toJson(cardMap)
                    val card = Gson().fromJson(json, Card::class.java)
    
                    adapter.add(CardItem(card))
                }
    
            }
    

    And that's my Card class

    data class Card(var courseId: String, var cardQuestion: String, var cardAnswer: String) {
         constructor() : this("", "", "")
    }
    

    I can also get the same outcome traversing through the dataSnapshot children this way:

    dataSnapshot.children.forEach {
    
            adapter.clear()
    
            val courseId = it.child("courseId").value as String
            val question = it.child("cardQuestion").value as String
            val answer = it.child("cardAnswer").value as String
    
            adapter.add(CardItem(Card(courseId, question, answer))
    }
    

    Thanks. :)

提交回复
热议问题