Saving JSON object to Firebase in Android
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);
It is so simple to also save JSON value on firebase. Let's say you have called your firebase reference
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/android/saving-data/fireblog");
Then you will pass your data with Map
objects. Map
keeps values with keys. In your case you will have a String
key and JSONObject
value.
Firebase userRef = ref.child("user");
Map<String, JSONObject> userMap= new HashMap<String, JSONObject>();
JSONObject tempObject = new JSONObject();
try{
tempObject.put("birthday","1992");
tempObject.put("fullName","Emin AYAR");
}catch(Exception e){
e.printStackTrace();
}
userMap.put("myUser", tempObject);
userRef .setValue(userMap);