Use custom JSON serializers with firebase

前端 未结 2 1648
醉梦人生
醉梦人生 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:27

    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 dataSnapshotValue = (HashMap) 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.

提交回复
热议问题