6

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 use a custom serializer.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Vinay Nagaraj
  • 1,162
  • 14
  • 26

2 Answers2

13

Update: I haven't had the time for checking out the documentation for the latest SDK but it seems like there are some options for JSON fields.


The getValue() in DataSnapshot returns a HashMap. So in any method of your Firebase listener, you could:

  1. Get the value of the DataSnapshot, which will return a HashMap:

    HashMap<String, JSONObject> dataSnapshotValue = (HashMap<String, JSONObject>) dataSnapshot.getValue();
    
  2. Cast the Hashmapto a valid JSON string, using Gson:

    String jsonString = new Gson().toJson(dataSnapshotValue);
    
  3. With this valid jsonString, cast it as needed:

    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(User.class, new UserSerializer());
    final Gson gson = gsonBuilder.create();
    User parsedUser = gson.fromJson(jsonString, User.class);
    

This gives you the possibility to use anything you want to cast an object from Firebase, you could either use custom serializers, an ExclusionStrategy, or retrieve some values from the HashMap directly.

RominaV
  • 3,335
  • 1
  • 29
  • 59
0

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<Card>(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. :)

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81