My server returns a list of objects in JSON. They might be Cat
s or Dog
s, for example.
When I know that they'll all be Cat
s, I can set the AutoBeanCodex
to work easily. When I don't know what types they are, though... what should I do?
I could give all of my entities a type field, but then I'd have to parse each entity before passing it to the AutoBeanCodex
, which borders on defeating the point. What other options do I have?
Just got to play with this the other day, and fought it for a few hours, trying @Category
methods and others, until I found this: You can create a property of type Splittable
, which represents the underlying transport type that has some encoding for booleans/Strings/Lists/Maps. In my case, I know some enveloping type that goes over the wire at design time, and based on some other property, some other field can be any number of other autobeans.
You don't even need to know the type of the other bean at compile time, you could get values out using Splittable
's methods, but if using autobeans anyway, it is nice to define the data that is wrapped.
interface Envelope {
String getStatus();
String getDataType();
Splittable getData();
}
(Setters might be desired if you sending data as well as recieving - encoding a bean into a `Splittable to send it in an envelope is even easier than decoding it)
The JSON sent over the wire is decoded (probably using AutoBeanCodex
) into the Envelope
type, and after you've decided what type must be coming out of the getData()
method, call something like this to get the nested object out
SpecificNestedBean bean = AutoBeanCodex.decode(factory,
SpecificNestedBean.class,
env.getData()).as();
The Envelope
type and the nested types (in factory
above) don't even need to be the same AutoBeanFactory
type. This could allow you to abstract out the reading/writing of envelopes from the generic transport instance, and use a specific factory for each dataType
string property to decode the data's model (and nested models).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With