Preface: I'm using Retrofit to handle my API calls and Realm(realm.io) to store the data.
The API im dealing with uses the following structure:
Array Response
{
"response":
[
{
"objectField1":"abc"
"objectField2":"abc"
"objectField3":"abc"
"objectField4":"abc"
},
{
"objectField1":"abc"
"objectField2":"abc"
"objectField3":"abc"
"objectField4":"abc"
}
]
}
Single object response
{
"response":
{
"objectField1":"abc"
"objectField2":"abc"
"objectField3":"abc"
"objectField4":"abc"
}
}
All api responses are contained in a response object either in an array (if result size > 1) or an object (if result size == 1).
I currently have my API call as follows:
@GET("/api/myEndpoint")
void getAllExampleObjects(Callback<MyRealmClass> callback);
How can I serialise the API response (handling both array and single object cases) to place them in my realm?
Christian from Realm here. If you have a single REST API call that can return both a list and a single object, you will have to do something manually. As colriot points out you will have to write your own GSON deserializer. For ideas how to write one see a very good answer in this SO post: How to handle parameters that can be an ARRAY or OBJECT in Retrofit on Android?
To get the objects into Realm you can use realm.copyToRealm(objects)
in the following way:
@GET("/api/myEndpoint")
void getAllExampleObjects(Callback<List<MyRealmClass>> callback);
Callback callback = new Callback() {
@Override
public void success(List<MyRealmClass> objects, Response response) {
realm.beginTransaction();
realm.copyToRealm(objects);
realm.commitTransaction();
}
@Override
public void failure(RetrofitError retrofitError) {
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With