shj shj - 1 month ago 37
JSON Question

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?

Answer

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!