Android: Realm + Retrofit - Serialize apiresponse

Preface: I use Retrofit to handle API calls and Realm (realm.io) to store data.

The following structure is used in the API:

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 answers are contained in the response object either in an array (if the size of the result> 1) or an object (if the size of the result == 1).

I currently have an API call as follows:

@GET("/api/myEndpoint")
void getAllExampleObjects(Callback<MyRealmClass> callback);

How can I serialize an API response (processing both an array and individual objects) to put them in my scope?

+4
source share
1 answer

. API REST, , , - . colriot, GSON. , , SO: , ARRAY OBJECT Android?

Realm, realm.copyToRealm(objects) :

@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) {

    }
};
+16

All Articles