Parsing JSON objects of unknown type from AutoBean to GWT

My server returns a list of objects in JSON. For example, they may be Cat or Dog s.

When I know that they will all be Cat s, I can easily customize AutoBeanCodex . When I donโ€™t know what they are, though ... what should I do?

I could provide all my objects with a type field, but then I would have to analyze each entity before passing it to AutoBeanCodex , which borders on the victory over the point. What other options do I have?

+6
source share
1 answer

You just need to play with it the other day, and struggled with it for several hours, trying @Category and others methods, until you find this: you can create a property of type Splittable , which represents the base transport type, which has some encoding for Boolean / Lines / Lists /Cards. In my case, I know some type of enveloping that passes through the wire during development and based on some other property, there can be any number of other auto-declarations in another field.

You donโ€™t even need to know the type of another bean at compile time, you can get the values โ€‹โ€‹using the Splittable methods, but when using autoblocks, itโ€™s nice to define data that is wrapped anyway.

 interface Envelope { String getStatus(); String getDataType(); Splittable getData(); } 

(Setters may be desirable if you are sending data, as well as receiving - encoding the bean in "Split for sending in an envelope, even easier than decoding it"

The JSON sent over the cable is decoded (possibly using AutoBeanCodex ) into an Envelope type, and after you decide which type should get out of the getData() method, call something like this to get a nested object

 SpecificNestedBean bean = AutoBeanCodex.decode(factory, SpecificNestedBean.class, env.getData()).as(); 

The Envelope type and nested types (in the factory above) do not even have to be the same AutoBeanFactory types. This can allow you to ignore reading / writing envelopes from a universal transport instance and use for each dataType property the value of a specific factory to decode the data model (and nested models).

+8
source

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


All Articles