如何将 Firebase 数据转换为 Java 对象...?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30933328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert Firebase data to Java Object...?
提问by Moosa Baloch
Using Firebase Library to send data to the server in the form Message(String, String)
added to the HashMap<String, Message>
使用 Firebase 库以Message(String, String)
添加到HashMap<String, Message>
Example:
例子:
Firebase fb = new Firebase(URL);
Firebase msgRef = fb.child("finished");
HashMap<String, Message> msgList = new HashMap<>();
Message msg = new Message(m, n);
msgList.put(HASHKEY, msg);
msgRef.push().setValue(msgList);
While receiving data with Firebase method addValueEventListener()
getting String in this Form
使用 Firebase 方法接收数据时,addValueEventListener()
在此表单中获取字符串
{ key = finished, value = {
-Js9Rn0uttjYIGdcv8I1={Moosa={message=email, name=Kamran}},
-Js9Vsmv6BnVzOzpl2L8={Moosa={message=msgs, name=Imran}},
-Js9WtQ8yeDwVxQMFCZb={Moosa={message=samsung, name=Samad}},
-Js9RarxoJPKn4RO2HaM={Moosa={message=Message, name=Moosa}},
-Js9b6f75lwwbsqQNJz0={Moosa={message=Qmobile, name=Bilal}},
-Js9aDxt8TlgTGUccuxu={Moosa={message=last, name=Moosa}}} }
How can I convert it into Message Object.....????
我怎样才能把它转换成消息对象.....????
采纳答案by Frank van Puffelen
There are two more way to get your data out of the Firebase DataSnapshot
that don't require using a Map<String, Object>
.
还有两种DataSnapshot
不需要使用Map<String, Object>
.
First appoach is to use the methods of DataSnapshot
to traverse the children:
第一种方法DataSnapshot
是使用 的方法来遍历孩子:
ref = new Firebase("https://my.firebaseio.com/messages").limitToLast(10);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
String name = (String) messageSnapshot.child("name").getValue();
String message = (String) messageSnapshot.child("message").getValue();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) { }
});
In the above snippet we use getChildren()
to get an Iterable
of your messages. Then we use child("name")
to get each specific child property.
在上面的片段中,我们getChildren()
用来获取Iterable
您的消息。然后我们使用child("name")
来获取每个特定的子属性。
The second approach is to use the built-in JSON-to-POJO serializer/deserializer. When you're sending the message list, the Message
objects inside it are serialized to JSON and stored in Firebase.
第二种方法是使用内置的 JSON-to-POJO 序列化器/反序列化器。当您发送消息列表时,其中的Message
对象会被序列化为 JSON 并存储在 Firebase 中。
To get them out of it again, you have to do the inverse:
为了让他们再次摆脱它,你必须做相反的事情:
ref = new Firebase("https://my.firebaseio.com/messages").limitToLast(10);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
Message message = messageSnapshot.getValue(Message.class);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) { }
});
In this second snippet, we're still using getChildren()
to get at the messages, but now we deserialize them from JSON straight back into a Message
object.
在第二个片段中,我们仍然使用getChildren()
获取消息,但现在我们将它们从 JSON 直接反序列化回一个Message
对象。
For a simple sample application using that last approach, have a look at Firebase's AndroidChat sample. It also shows how to efficiently deal with the list of messages (hint: FirebaseListAdapter
).
对于使用最后一种方法的简单示例应用程序,请查看Firebase 的 AndroidChat 示例。它还展示了如何有效地处理消息列表(提示:)FirebaseListAdapter
。
回答by M090009
So if you wanna get the messages you can do the following:
因此,如果您想收到消息,可以执行以下操作:
for (DataSnapshot child : dataSnapshot.getChildren()){
//child is each element in the finished list
Map<String, Object> message = (Map<String, Object>)child.getValue();
Message msg = new Message((String) message.getValue().get("message"),
(String) message.get("name"));
}
回答by Moosa Baloch
Iterating the values of dataSnapshot and getting Children using nested for loop to iterate the child elements of children and getting the Required Value...
迭代dataSnapshot的值并使用嵌套for循环获取子项以迭代子项的子元素并获取所需的值...
for (DataSnapshot child : dataSnapshot.getChildren()) {
for (DataSnapshot single : child.getChildren()) {
Map<String, Object> map = (Map<String, Object>) single.getValue();
String a = (String) map.get("message");
String b = (String) map.get("name");
textView.append(b + " -- " + a + "\n");
}
}
回答by Sergio
You could make it using a ChildEventListener
instead of a ValueEventListener
.
您可以使用 aChildEventListener
而不是a来制作它ValueEventListener
。
For example. I have a class called match with 3 string properties {id, name, photoUrl}
then I add all the values in a List
. Instead of using a for loop it works for me with this code.
例如。我有一个名为 match 的类,具有 3 个字符串属性,{id, name, photoUrl}
然后我将所有值添加到List
. 它不使用 for 循环,而是使用此代码对我有用。
Query queryRef = mDatabase.child("users").child(user.getUid()).child("matches");
ChildEventListener listener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Match match = dataSnapshot.getValue(Match.class);
matchList.add(match);
mAdapter = new MatchAdapter(getContext(), matchList);
recyclerView.setAdapter(mAdapter);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d("MESSAGEFRAGMENT", "CHILDCHANGE");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
queryRef.addChildEventListener(listener);
回答by Alok Gupta
Use this code if you want to convert firebase object to json using Gson Library :
如果您想使用 Gson 库将 firebase 对象转换为 json,请使用此代码:
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object object = dataSnapshot.getValue(Object.class);
String json = new Gson().toJson(object);
Example example= new Gson().fromJson(json, Example.class);
Log.e("json","json: " + example.getGlossary());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
This will convert complete Database Structure to String json and then json to class object using Gson Lib
这将使用 Gson Lib 将完整的数据库结构转换为字符串 json,然后将 json 转换为类对象