使用JAXB将JSON转换为POJO

问题描述:

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

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对象只与最外层类(EPCISDocumentType),但0的内容来。我正尝试这样的:

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

的问题是为什么发生这种情况,I'm使用完全相同的库做元帅,但我不能解组回相同的内容。

我使用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); 

当您想要编组/解组对象的列表,它只能如果你把名单的包装。

杰克逊比jaxb更高效。 检查这些测试:http://tuhrig.de/jaxb-vs-gson-and-jackson/