简体   繁体   中英

Java Android Realtime firebase class from Snapshot

在此处输入图像描述

In firebase, I have a class User with values like deleted or email . To retrieve an instance of this class from realtime firebase , I do : User user = datasnapshot(User.class). I don t want to use Hashmap since User class has like 40 elements . In the example in the description, in the db , i have a key : description_labels with several sub keys . If i make a snap in this case, i will get all correct values but a warning : no getter/field for description_labels .

I would like to either handle a dictionnary(swift like) in which i would remove the "description_labels" field or somehow add an element to User class . So far, i tested, hashmap, datasnapShot as a nature for the Java class field without success .

Doing User user = dataSnapshot.getValue(User.class); would trigger a warning in the console . Can be bugging if a lot of keys are not used . After some research , i found a possible solution :

         try {

                        Gson gson = new Gson();
                        JSONObject object = getJsonFromMap((Map<String, Object>) dataSnapshot.getValue());
                        object.remove("description_labels");
                        User user = gson.fromJson(object.toString(), User.class);

                    } catch (JSONException e) { }


 private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value = getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    return jsonData;
}

This way ,non mandatory keys can be removed and no need to fill Hashmap (can be quite a lot of code if User has a lot of sub values)

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