将自定义JSON序列化程序与Firebase一起使用 [英] Use custom JSON serializers with firebase
问题描述
在使用DataSnapshot.getValue()时,是否可以获取JsonObjects或Json格式的字符串?也许我没有足够彻底的搜索,但我找不到一个方法来使用自定义序列化程序。
解决方案 更新:
我没有时间查看最新SDK的文档,但看起来像有一些JSON字段的选项。
在 DataSnapshot
中的 getValue()
返回一个 HashMap
。
因此,在Firebase侦听器的任何方法中,您都可以:
-
获取DataSnapshot的值,返回一个
HashMap
:HashMap< String,JSONObject> dataSnapshotValue =(HashMap< String,JSONObject>)dataSnapshot.getValue();
-
将
Hashmap
使用Gson:
字符串jsonString = new Gson()。toJson(dataSnapshotValue);
-
使用这个有效的
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:
Get the value of the DataSnapshot, which will return a
HashMap
:HashMap<String, JSONObject> dataSnapshotValue = (HashMap<String, JSONObject>) dataSnapshot.getValue();
Cast the
Hashmap
to a valid JSON string, using Gson:String jsonString = new Gson().toJson(dataSnapshotValue);
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屋!