Marina R Albuquerque
Marina R Albuquerque

Reputation: 127

Import JSON in Realtime Database programmatically, not manually

I want to be able to import a JSON file to Firebase with a button in my app. I know that you can add a JSON file manually in the Firebase Console, but in this case, I want to let my user import a JSON file with a button and update the info in Realtime Database. Can someone help me?

Upvotes: 2

Views: 922

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 139029

I want to be able to import a JSON file to Firebase manually

There is no API for doing that. If you want to let the user the possibility to add the content of a JSON file to the Realtime Database, then you should write some code for that. Meaning that you need to implement an option in which the user can upload the JSON file to the local storage, then in your app's code, you should read the file and get the data as JSON String. To convert it to a Map, you can simply use:

val jsonObj = JSONObject(jsonString)
val map = jsonObj.toMap()

Now, to write this Map object into the Realtime Database, in a location that corresponds only to a specific user, assuming that you are using Firebase Authentication, please use the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser?.uid
val rootRef = FirebaseDatabase.getInstance()
val uidRef = rootRef.child("users").child(uid)
uidRef.setValue(map).addOnCompleteListener(/* ... /*)

Upvotes: 1

Tarik Huber
Tarik Huber

Reputation: 7418

You would need first to convert the json to a map and then save it directly to the path you want:

val jsonMap = Gson().fromJson<Any>(stringJson, object : TypeToken<HashMap<String, Any>>() {}.type)

Firebase ref = new Firebase(YOUR_FIREBASE_PATH);
ref.setValue(jsonMap );

Upvotes: 1

Related Questions