Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve firebase data as json

I would like to retrieve data stored in firebase database but in proper Json format, the problem is when using String.valueOf(dataSnapshot.getValue()) it is not the correct json format. For example, if the the data

{
  "properties" : {
     "last_update" : "15-02-2017 02:48:00 pm",
     "last_update_code" : "1258884"  
  } 
}

the returned value becomes like that

properties = {last_update = 15-02-2017 02:48:00 pm,last_update_code = 1258884}

without the quotes or (:) .

so it there a way to get the data as string in the first format?

like image 895
Aya Avatar asked Dec 04 '22 22:12

Aya


2 Answers

You'll get the returned value that you're getting when you try to convert a json to String.

So, instead of doing that, you can use one of the following methods :-

First :-

String lastUpdate = dataSnapshot.child(last_update).getValue(String.class);
String last_update_code = dataSnapshot.child(last_update_code).getValue(String.class);

Second :-

Define a POJO that maps to your Json. After that, use the following code.

YourPOJO yourPOJO = dataSnapshot.getValue(YourPOJO.class);

You can read more about it here.

like image 40
Rohan Stark Avatar answered Dec 11 '22 16:12

Rohan Stark


Here is what I do. First, create a java object from DataSnapshot then get JSON from that object using Gson.

Object object = datasnapshot.getValue(Object.class);
String json = new Gson().toJson(object);
like image 117
minhazur Avatar answered Dec 11 '22 16:12

minhazur