简体   繁体   中英

Converting Firebase json to Java object

Ever since I started working with Firebase Real time database, trivial tasks are becoming increasingly difficult.

I have the following JSON structure in the Firebase DB.

{
    "EmailId": "sample.co@email.com",
    "Locations": {
        "-Kci2Ov9_lI2d5RUnvYT": {
            "Latitude": "17",
            "Longitude": "78",
            "RecordedDateTime": "1254"
        },
        "-Kci77tuFbWP5Vdt4keF": {
            "Latitude": "17",
            "Longitude": "78",
            "RecordedDateTime": "1254"
        }
    },  
    "MobileNumber": 1234567890,
    "UserName": "Firstname Lastname"
}

my firebase query from java returns a DataSnapshot which I know contains the above structure. I have the following Java object which I think maps to the above structure.

public class User {
    private String EmailId;
    private String MobileNumber;
    private String UserName;
    private ArrayList<UserLocationInfo> userLocationInfos;

    //Constructor, getters and setters are below.
}

But the code fails whenever I try to read the DataSnapshot into this object using the following code.

dataSnapshot.getValue(User.class)

Error:

com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String.

Please advise on the Java class and also why am I getting this convertion error when Firebase stores data as json whose values are Strings?

Your MobileNumber was saved as a long value and you're trying to retrieve it as a String. You can change it's data type on your POJO:

public class User {
    private String EmailId;
    private long MobileNumber;
    private String UserName;
    private ArrayList<UserLocationInfo> userLocationInfos;

    //Constructor, getters and setters are below.
}

Or turning into a String on your Database, by adding quotation marks:

"MobileNumber": "1234567890",
"UserName": "Firstname Lastname"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM