How do you save/store objects in SharedPreferences on Android?

后端 未结 20 2467
野趣味
野趣味 2020-11-22 13:35

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

<
20条回答
  •  名媛妹妹
    2020-11-22 14:20

    I've used jackson to store my objects (jackson).

    Added jackson library to gradle:

    api 'com.fasterxml.jackson.core:jackson-core:2.9.4'
    api 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
    api 'com.fasterxml.jackson.core:jackson-databind:2.9.4'
    

    My test class:

    public class Car {
        private String color;
        private String type;
        // standard getters setters
    }
    

    Java Object to JSON:

    ObjectMapper objectMapper = new ObjectMapper();
    String carAsString = objectMapper.writeValueAsString(car);
    

    Store it in shared preferences:

    preferences.edit().car().put(carAsString).apply();
    

    Restore it from shared preferences:

    ObjectMapper objectMapper = new ObjectMapper();
    Car car = objectMapper.readValue(preferences.car().get(), Car.class);
    

提交回复
热议问题