Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning polymorphic objects from Google Cloud endpoints

I just tried to use polymorphism for entities for creating classes with hierarchy using objectify. For example, I have a base Entity called Animal and have subclasses for this named Mammal and Reptile which is also entities.
And when I try to store the data and retrieve it, it works fine and I am able to convert from base Animal class to Mammal or Reptile.

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

Actually Google Cloud endpoint is creating another model type which is actually returned as JSON in the endpoints for which is different from our entities and inheritance is not preserved in those model classes.

Basically I need to query for all the animals and in client side based on the type of the object whether its Mammal or Reptile I will show the UI accordingly.

Here is a sample code.

I have two classes Animal and Mammal. And 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 that animal object which might be a Mammal instance and I should convert this to Mammal or any other subclass of Animal based on its instance on the client side.

Does anyone have any solution or workaround for this problem?

Below is the JSON response for retrieving list of animals. But I was not able 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\""
}
like image 750
Kalyan Avatar asked Jul 02 '26 08:07

Kalyan


1 Answers

Unfortunately cloud endpoints don't use your actual classes when serializing/deserializing it's JSONs. It uses a generated "flat" POJO class which is completely unaware of any hierarchy you have in your original class. So by the time you get an "Animal" class on your Android client there i not relation whatsoever to the other classes.

Your only hope would be to send and additional parameter indicating the object's actual kind and assemble the corresponding instance manually on the Android size.

like image 149
jirungaray Avatar answered Jul 03 '26 20:07

jirungaray