Skip to content

Instantly share code, notes, and snippets.

@jocollet
Last active April 12, 2016 09:53
Show Gist options
  • Save jocollet/91d78da9f47922dc26d6 to your computer and use it in GitHub Desktop.
Save jocollet/91d78da9f47922dc26d6 to your computer and use it in GitHub Desktop.
Example of TypeAdapters to convert json to Realm objects
// ref : https://gist.github.com/cmelchior/1a97377df0c49cd4fca9
private void initGson() {
Type tokenInt = new TypeToken<RealmList<RealmInt>>(){}.getType();
Type tokenString = new TypeToken<RealmList<RealmString>>(){}.getType();
Type tokenDate = new TypeToken<Date>(){}.getType();
mGson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.ssssss")
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(tokenDate, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return DateTime.parse(json.getAsString()).toDate();
}
})
.registerTypeAdapter(tokenInt, new TypeAdapter<RealmList<RealmInt>>() {
@Override
public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException {
}
@Override
public RealmList<RealmInt> read(JsonReader in) throws IOException {
RealmList<RealmInt> list = new RealmList<>();
in.beginArray();
while (in.hasNext()) {
RealmInt ri = new RealmInt();
ri.setVal(in.nextInt());
list.add(ri);
}
in.endArray();
return list;
}
})
.registerTypeAdapter(tokenString, new TypeAdapter<RealmList<RealmString>>() {
@Override
public void write(JsonWriter out, RealmList<RealmString> value) throws IOException {
}
@Override
public RealmList<RealmString> read(JsonReader in) throws IOException {
RealmList<RealmString> list = new RealmList<>();
in.beginArray();
while (in.hasNext()) {
RealmString rs = new RealmString();
rs.setVal(in.nextString());
list.add(rs);
}
in.endArray();
return list;
}
})
.create();
}
@Sadmansamee
Copy link

how can we use it? please share a simple snippet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment