Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving JSON object to Firebase in Android

I am new to firebase, and I am trying to put JSON object data into my Firebase. I know how to put data as a class object into Firebase, but I want to put JSON object data.

Is there any way to put JSON object data into Firebase without converting it as a POJO?

like image 990
inin Avatar asked Apr 04 '16 06:04

inin


2 Answers

Yes, you can achieve this. Start by converting your json to a string then do the following:

  String jsonString; //set to json string
  Map<String, Object> jsonMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>() {}.getType());

I am using the "updateChildren" method because I want the JSON object added directly to the root of my child object

  firebaseDatabaseRef.child("users").child(uid).updateChildren(jsonMap);

If you don't care or you would like to set a new node, use

 firebaseDatabaseRef.child("users").child(uid).child({your new node}).setValue(jsonMap);
like image 193
GraSim Avatar answered Sep 28 '22 05:09

GraSim


As you've tagged android in your question, so I guess you want to put some data in your firebase database from the Android client.

You've some JSON data and you want it to store in firebase database right? This is the step by step procedure to get it done.

I don't really know why are you trying to avoid POJO. It makes the total operation more simplified. Now let us assume you've a JSON string. You need to map your JSON to a java class to put it directly in the firebase. Firebase stores the data in a JSON-like format which is easily understandable.

I use Gson to map a JSON string to a specific java object. Its the easiest method I've found so far needs few lines of coding.

Gson gson = new Gson();
YourPOJO myPOJO = gson.fromJson(jsonString, YourPOJO.class);

Now you've mapped your JSON string to myPOJO object successfully. You're ready to put this object in your Firebase database now.

Lets take the reference to your Firebase database and then call setValue in that specific node where you want put the data.

Firebase ref = new Firebase(YOUR_FIREBASE_REF);
ref.setValue(myPOJO);

Simple!

like image 45
Reaz Murshed Avatar answered Sep 28 '22 05:09

Reaz Murshed