I'm current using RealmList
public class MyModel extends RealmObject {
@PrimaryKey
private int id;
@SerializedName("exampleRealmList")
@Expose
private RealmList<MyObject> exampleRealmList;
(...)
}
Result sent to the server using retrofit 2:
{
"exampleRealmList": [],
}
I already used the following code as sugested in http://stackoverflow.com/a/34736978/706833 despite no success.
gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
});
Realm version(s): 1.1.0
Retrofit version: 2.0.1
retroGsonConverterVersion : 2.0.1
Android Studio version: 2.2 RC2
You should call realm.copyFromRealm(realmObject) on the object you're serializing with GSON before you serialize it with GSON
service.callMethod(realm.copyFromRealm(realmObject));
You might run into one limitation of our RealmList(). It cannot be null. see https://realm.io/docs/java/1.2.0/api/io/realm/annotations/Required.html .
Which means if it is a managed RealmList, it will always return as a empty list even you set it to null.
The TypeAdapter of Gson might be useful for you, you can pass a gson instance to Retrofit that will always serialize your empty list as null or not even create the field (as you wish).
See this for creating the typeadapter: http://stackoverflow.com/questions/18491733/gson-serialize-field-only-if-not-null-or-not-empty
And this is how you put the gson into the retrofit instance:
Gson gson = getYourNiceGsonInstance();
RETROFIT = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson)).
Yeah, trying to make a custom converter for a specific realmList object, will post the results then.
Thanks guys!
Cool, no problem! Although, I think it should be fine in the server side to receive a empty list instead of null.
No, If the list simbolizes the difference of never had items (null), or do not have items currently (empty). As the effort of changing the server implementation is greater than changing on client side.
Just a follow up, this worked
public class MyObjectListTypeAdapter extends TypeAdapter<RealmList<MyObject>> {
@Override public void write(JsonWriter out, RealmList<MyObject> src) throws IOException {
if(src.isEmpty()){
out.nullValue();
}else {
out.beginArray();
for (MyObject object : src) {
out.value(object.getValue());
}
out.endArray();
}
}
@Override public RealmList<MyObject> read(JsonReader in) throws IOException {
return new RealmList<>();
}
}
Thanks!
Most helpful comment
Just a follow up, this worked
Thanks!