在 GWT 上使用 AutoBean 解析未知类型的 JSON 对象 [英] Parsing JSON objects of unknown type with AutoBean on GWT
问题描述
我的服务器以 JSON 格式返回对象列表.例如,它们可能是 Cat
s 或 Dog
s.
My server returns a list of objects in JSON. They might be Cat
s or Dog
s, for example.
当我知道它们都是 Cat
时,我可以将 AutoBeanCodex
设置为轻松工作.但是,当我不知道它们是什么类型时……我该怎么办?
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?
我可以给我的所有实体一个类型字段,但是我必须在将每个实体传递给 AutoBeanCodex
之前解析每个实体,这接近于击败这一点.我还有什么其他选择?
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?
推荐答案
前几天刚玩这个,和它斗争了几个小时,尝试了 @Category
方法和其他方法,直到我发现了这一点:您可以创建一个 Splittable
类型的属性,它表示具有布尔值/字符串/列表/映射的一些编码的底层传输类型.就我而言,我知道一些在设计时通过线路的包络类型,并且根据其他一些属性,其他一些字段可以是任意数量的其他 autobean.
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.
您甚至不需要在编译时知道其他 bean 的类型,您可以使用 Splittable
的方法获取值,但是如果无论如何使用 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();
}
(如果您在发送数据的同时接收数据,则可能需要设置器 - 将 bean 编码为 `Splittable 以在信封中发送它比解码它更容易)
(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)
通过线路发送的 JSON 被解码(可能使用 AutoBeanCodex
)到 Envelope
类型,并且在您确定必须从 Envelope
类型中出来之后code>getData() 方法,调用这样的东西把嵌套的对象取出来
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();
Envelope
类型和嵌套类型(在上面的 factory
中)甚至不需要是相同的 AutoBeanFactory
类型.这可以让您从通用传输实例中抽象出信封的读/写,并为每个 dataType
字符串属性使用特定的工厂来解码数据的模型(和嵌套模型).
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).
这篇关于在 GWT 上使用 AutoBean 解析未知类型的 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!