Polymorphism or Inheritance in JSON with Java and Ruby Polymorphism or Inheritance in JSON with Java and Ruby json json

Polymorphism or Inheritance in JSON with Java and Ruby


To make it work you must both embed some object type information in data (where it is only useful for deserializing) and usually use external schema definition which otherwise would not be needed (like XML Schema for xml; since that's basically a generic type system).This has same problems as ORM has: Hibernate has to use ugly work-arounds (n+1 - way joins, "super tables" or discriminator fields).

Or another way to put it: data mapping/binding is not quite the same as object serialization/deserialization (latter tries to preserve more of object identity).

Here I am assuming that what you want is basically something like:

Pet pet = mapper.readValue(jsonString, Pet.class);// (and possibly get an exception if Pet is an abstract class...)Leash l = ((Dog) pet).getLeash();

If this is not the case, you could just simply bind to Dog

Dog dog = mapper.readValue(jsonString, Dog.class);

So anyway: Jackson project has feature request for doing just this, which allow you to do what (I think) you want.

However, this solution will mostly work for Java, as there is no standard way of passing Object type info within JSON. With XML this can sort of be done with XML Schema defined "xsi:type" attribute; which identifies Schema type, which is then mapped to class (yes, rather complicated way, but it does work).

UPDATE: Jackson 1.5 added support for this (i.e. implemented JACKSON-91 feature request), so it can be used for generating type identifiers, to allow proper handling of polymorphic types. It should work with non-Java systems too, given that you can fully configure details of how type information is to be included; and is NOT limited to using Java class names.


I've not had that much experience using JSON other than for fixtures in django, but in that instance I just have a "model" key, with the associated value.

It is then up to the program that is interpreting the objects to determine their type and inheritance hierarchy.

What I'm trying to say is that it is irrelevant what methods are available, as this doesn't need to be serialised. Only the object's name and attributes.

-- update

After reading your question again, it seems like your process is deserialising into the parent class, rather than the actual class. Since your dog class inherits from pet, you just want to make sure your deserialiser is creating objects of the most specialised class.

I don't know about the Jackson library, but if you can set it to have a type of model field, then that might be the go.