Returning polymorphic objects from Google Cloud endpoints

I just tried to use polymorphism on objects to create classes with hierarchy using objectify. For example, I have a base Entity called Animal and there are subclasses for that name Mammal and Reptile, which are also entities.
And when I try to store data and retrieve it, it works great and I can convert from the base Animal class to Mammal or Reptile.

But when I try to return a list of animals in google endpoints, this inheritance is not preserved. And I could not convert from Animal class to Mammal or Reptile on the client side.

In fact, the google cloud endpoint creates a different model type that is actually returned as JSON at the endpoints for which it is different from our entities, and inheritance is not preserved in these model classes.

Basically, I need to query all animals and client-side depending on the type of object, regardless of whether a mammal or a reptile renders it the appropriate interface.

Here is some sample code,

I have two classes: Animals and Mammals. And the mammal is a subclass of Animal.

Animal annie = new Animal();
annie.name = "Annnnn";
ofy().save().entity(annie).now();

Mammal mam = new Mammal();
mam.name = "Mammmaaaal";
mam.longHair = true;
ofy().save().entity(mam).now();

// This will return the Cat
Animal fetched = ofy().load().type(Animal.class).id(mam.id).now();
return Animal;

      

I will return this animal object which can be a Mammal instance and I have to convert it to Mammal or any other Animal subclass based on its client side instance.

Does anyone have a solution or workaround for this problem?

Below is the json response for getting a list of animals. But I was unable to convert the animal object to Mammal on the Android client side.

{
 "items": [      
  {
   "id": "5631986051842048",
   "name": "mammm",
   "longHair": true,
   "kind": "animalApi#resourcesItem"
  },
  {
   "id": "5697423099822080",
   "name": "Animalll",
   "kind": "animalApi#resourcesItem"
  }
 ],
 "nextPageToken":     "CjwSNmofc35tb3ZpZWFkZGljdC12Mi1kZWJ1Zy1jb2RlaGFyZHITCxIGQW5pbWFsGICAgIDruI8KDBgAIAA",
 "kind": "animalApi#resources",
 "etag": "\"cZTcM4l5N_SjrKcEhGkKJEl9rU4/rs8BjIS52gHgN0B1UGEEi2DERwE\""
}

      

+3


source to share


1 answer


Unfortunately cloud endpoints do not use your actual classes when serializing / deserializing JSON. It uses the generated "flat" POJO class that is completely unaware of any hierarchy in your original class. So by the time you get the "Animal" class on your Android client, I'm not one of the other classes.



Your only hope is to send in an additional parameter specifying the actual view of the object, and assemble the corresponding instance manually to fit Android.

+1


source







All Articles