Andrew Heschl
Andrew Heschl

Reputation: 359

How can I write a JSONObject to a firebase database node

I am currently trying to migrate an app to firebase from a SQLDatabase. I have done all the work to convert the database to a JSONObject. Is there a way I can just fill a user node in firebase with this object?

I tried to write the JSONObject with

database.getReference("/" + user.getUid() + "/").setValue(jsonObject);

this returns the error

com.google.firebase.database.DatabaseException: No properties to serialize found on class org.json.JSONObject

I'm trying to avoid breaking apart the object and posting individual values seperatly because this could be error prone and I can't risk corrupting data with a messed up loop... Thanks for any help.

Upvotes: 0

Views: 250

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

You can convert the json into an object using ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonObject.toString(), User.class);

https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html

Then you can use the instance of the class User in setValue():

database.getReference("/" + user.getUid() + "/").setValue(user);

From the docs:

In addition, you can set instances of your own class into this location, provided they satisfy the following constraints:

The class must have a default constructor that takes no arguments

The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized

Upvotes: 3

Related Questions