Polymorphism or inheritance in JSON with Java and Ruby

In context, we store most of our data as JSON strings. This works well with Hadoop on the backend and is easily handled in Ruby on the front panel. My data types follow a natural pattern for inheritance.

For simplicity, let's say I have a Pet class and a FeedPet process that feeds a pet. I also have a WalkDog process that applies only to a dog, which is a kind of pet. My data is organized in such a way that I never have to worry about trying to walk with a pet that is not a dog.

What I would like to do is that Pet and Dog extends Pet, and the dog has an additional getLeash () method, but I cannot figure out how to match this with JSON.

Instead, I have a Pet class with a hashmap of these views, so the WalkDog process will call pet.getSpeciesData ("leash") instead of dog.getLeash ().

I can create Dog extends Pet, and I can serialize it to JSON using the Jackson library. The JSON object will have a rotation field. But suppose I want to feed all the pets. All pets have a getFood () method. Thus, the FeedPet process deserializes the objects in Pet. But this is losing the battlefield.

The WalkDog process can do this because he knows that all of his input will be Dogs, so he can read it as a Dog and write it as a Dog.

Is there a way to serialize java objects for JSON so that I can save their type? I think something like Rails unidirectional inheritance, but that should be what the JSON libraries understand.

+3
2

, ( ) , (, XML Schema xml, ). , ORM: Hibernate (n + 1-way join, "super tables" ).

: / , / ( ).

, - :

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

, Dog

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

: Jackson , , ( ) .

Java, JSON. XML XML Schema, "xsi: type"; , (, , ).

UPDATE: Jackson 1.5 (.. JACKSON-91), , . -Java-, , , ; Java.

+2

JSON, dfango django, "" .

, .

, , , , , . .

-

, , . , , .

, , .

0

Source: https://habr.com/ru/post/1706078/


All Articles