6

我的客户端有一个 javascript 对象列表,它是用户已执行的“事件”列表。当用户准备好时,我想将其发送到服务器。事件的顺序很重要,因此保留列表顺序是必要的。

我想做的是有一个 JSON 库(不介意哪个)将 JSON 绑定到我的 Java 代码中的一些 Event 对象,其中 Event 是一个抽象类,我有 3 个具体类都扩展 Event (让我们说 EventA、EventB 和 EventC)。

理想的情况是这样的

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

其中可能包含项目列表,例如

[eventA, eventC, eventA, eventA, eventB]

这是可能的,还是我必须手动检查 JSON 树,并反序列化 json 数组的各个元素?

4

4 回答 4

6

JSON 对象只是键/值对,不包含类型信息。这意味着无法自动识别 JSON 对象的类型。你必须在服务器端实现一些逻辑来找出你正在处理什么样的事件。

我建议使用一个工厂方法,它接受一个 json 字符串,解析它以找出它是什么类型的 Event,构建正确子类的 Event 对象并返回它。

于 2012-08-29T15:30:05.087 回答
1

您可以使用 Genson 库http://code.google.com/p/genson/。如果 json 是使用 Genson 生成的,它可以反序列化为具体类型。否则你只需要添加类似 [{"@class":"my.java.class", "the rest of the 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);

编辑 这里是 wiki 示例http://code.google.com/p/genson/wiki/GettingStarted#Interface/Abstract_classes_support

于 2012-08-29T16:50:56.140 回答
1

为什么不使用杰克逊 json 库

它是一个具有数据绑定功能的完整对象/JSON 映射器。

它速度快、占用空间小、有文档记录、过度使用,还有许多其他你会喜欢的东西!

于 2012-08-29T16:59:03.270 回答
0

如果 json 由同一个库编码,我开始了一个实现所需功能(用于 json 和 xml)的库:

https://github.com/giraudsa/serialisation

使用它, MyObject myObject = new SpecialisedObject();

String json = JsonMarshaller.ToJson(myObject);
MyObject myClonedObject = JsonUnMarshaller(json);
于 2015-07-16T20:51:31.277 回答