将自定义JSON序列化程序与Firebase一起使用 [英] Use custom JSON serializers with firebase

查看:123
本文介绍了将自定义JSON序列化程序与Firebase一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用DataSnapshot.getValue()时,是否可以获取JsonObjects或Json格式的字符串?也许我没有足够彻底的搜索,但我找不到一个方法来使用自定义序列化程序。

解决方案

更新
我没有时间查看最新SDK的文档,但看起来像有一些JSON字段的选项




DataSnapshot 中的 getValue()返回一个 HashMap
因此,在Firebase侦听器的任何方法中,您都可以:


  1. 获取DataSnapshot的值,返回一个 HashMap

      HashMap< String,JSONObject> dataSnapshotValue =(HashMap< String,JSONObject>)dataSnapshot.getValue(); 


  2. Hashmap 使用Gson:

     字符串jsonString = new Gson()。toJson(dataSnapshotValue); 


  3. 使用这个有效的 jsonString 根据需要转换它:

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


要从Firebase投射对象,您可以使用自定义序列化器, ExclusionStrategy ,或直接从 HashMap 中检索一些值。


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.

解决方案

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.

这篇关于将自定义JSON序列化程序与Firebase一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆