使用 JAXB 将 JSON 转换为 POJO

Converting JSON to POJO using JAXB

我正在使用 ElasticSearch 来存储一些与对象发生的事件相关的数据,一个跟踪模型。为此,我使用 JAXB 使用 XSD 文件生成模型 classes。 我可以轻松地将数据保存在 ES 上,将 XML 中的数据数据转换为 POJO,然后再转换为 JSON。 我遇到的问题是取回数据。我正在尝试使用相同的逻辑 JSON 到 POJO(使用 JAXB)和 POJO 到 Web 服务上的 XML。像那样:

JAXBContext jc = JAXBContext.newInstance(EPCISDocumentType.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller.setProperty("eclipselink.json.include-root", true);
String eventJSON = elasticEvent.getSpecific("event", "raw", eventID);

字符串带有预期的事件,但是当我尝试转换为 POJO 时,该对象仅带有最外层的 class (EPCISDocumentType),但内容为 0。我正在尝试这样:

StreamSource eventStream = new StreamSource(new StringReader(eventJSON));
EPCISDocumentType foundEvent =  unmarshaller.unmarshal(eventStream,EPCISDocumentType.class).getValue();

问题是为什么会这样,我使用完全相同的库来执行 Marshal,但我无法将其解组回相同的内容。

我使用 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) 进行封送处理和解封处理。它更容易使用。 见下文:

ObjectMapper mapper = new ObjectMapper();
//Get the json as String
String objectAsJsonString= mapper.writeValueAsString(foundEvent);
//Create the object from the String 
EPCISDocumentType foundEvent = mapper.readValue(objectAsJsonString,EPCISDocumentType.class);

当您有想要的对象列表时 marshal/unmarshal,只有将列表放入包装器中它才有效。

此外,jackson 的性能比 jaxb 更高。 检查这些测试:http://tuhrig.de/jaxb-vs-gson-and-jackson/