Save custom object in shared preferences

前端 未结 1 1264
轮回少年
轮回少年 2021-01-13 09:43

I want to save a custom object myObject in shared preferences. Where this custom object has ArrayList. This anotherCu

1条回答
  •  有刺的猬
    2021-01-13 10:14

    Link posted by damian was helpful to solve my problem. However, in my case there was no view component in custom object.

    According to my observation if you find multiple JSON fields for ANY_VARIABLE_NAME, then it is likely that it is because GSON is not able to convert the object. And you can try below code to solve it.

    Add below class to to tell GSON to save and/or retrieve only those variables who have Serialized name declared.

    class Exclude implements ExclusionStrategy {
    
        @Override
        public boolean shouldSkipClass(Class arg0) {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            SerializedName ns = field.getAnnotation(SerializedName.class);
            if(ns != null)
                return false;
            return true;
        }
    }
    

    Below is the class whose object you need to save/retrieve. Add @SerializedName for variables that needs to saved and/or retrieved.

    class myClass {
        @SerializedName("id")
        int id;
        @SerializedName("name")
        String name;
    }
    

    Code to convert myObject to jsonString :

    Exclude ex = new Exclude();
        Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
    String jsonString = gson.toJson(myObject);
    

    Code to get object from jsonString :

    Exclude ex = new Exclude();
    Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
    myClass myObject = gson.fromJson(jsonString, myClass.class);
    

    0 讨论(0)
提交回复
热议问题