JSON Polymorphism

I have a list of javascript objects on my client side that are a list of "events" that the user has executed. When the user is ready, I want to send it to the server. The order of events is important, so you must keep the order of the list.

What I would like to do is to have a JSON library (regardless of any) to associate JSON with some Event objects in my Java code, where Event is an abstract class, and I have 3 specific classes, all extend Event (lets say EventA, EventB and EventC).

The perfect scenario would look like

List<Event> events = jsonlibrary.deserialise(jsonString); 

which may contain a list of items such as

 [eventA, eventC, eventA, eventA, eventB] 

Is this possible, or do I need to manually check the JSON tree and deserialize the individual elements of the json array?

+6
source share
4 answers

JSON objects are simply key / value pairs and do not contain type information. This means that automatic JSON object type detection is not possible. You need to implement some server-side logic to find out what event you are facing.

I would suggest using the factory method, which takes a json string, parses it to find out which event it is, creates an Event object from the corresponding subclass, and returns it.

+6
source

You can use the Genson library http://code.google.com/p/genson/ . It can be deserialized to specific types if json was created using Genson. Otherwise, you only need to add something like [{"@class": "my.java.class", "other properties"} ...]

 // an example abstract class Event { String id; } class Click extends Event { double x, y; } // you can define aliases instead of plain class name with package (its a bit nicer and more secure) Genson genson = new Genson.Builder().setWithClassMetadata(true).addAlias("click", Click.class).create(); String json = "[{\"@class\":\"click\", \"id\":\"here\", \"x\":1,\"y\":2}]"; // deserialize to an unknown type with a cast warning List<Event> events = genson.deserialize(json, List.class); // or better define to which generic type GenericType<List<Event>> eventListType = new GenericType<List<Event>>() {}; events = genson.deserialize(json, eventListType); 

EDIT here is an example wiki http://code.google.com/p/genson/wiki/GettingStarted#Interface/Abstract_classes_support

+1
source

Why not use the Jackson json library ?

This is a complete Object / JSON Mapper with data binding function.

This is a quick, small footprint, documented, excessive, and much more that you will like!

+1
source

I started a library that implements the desired fonctionality (for json and xml) if json is encoded with the same library:

https://github.com/giraudsa/serialisation

to use it, MyObject myObject = new SpecialisedObject();

 String json = JsonMarshaller.ToJson(myObject); MyObject myClonedObject = JsonUnMarshaller(json); 
0
source

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


All Articles