2016-04-27 159 views
0

我正在使用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使用完全相同的庫做元帥,但我不能解組回相同的內容。

回答

0

我使用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/