I want to save a custom object myObject
in shared preferences. Where this custom object has ArrayList
. This anotherCu
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);