2012-07-22 57 views
3

我目前正在使用JAXB作爲我正在開發的項目,希望將我的庫存檔的xml轉換爲存檔的json,以便在我的項目中執行操作。我想我會使用Jettison,因爲它似乎是easier to implement,因爲它實際上與JAXB一起工作;然而,看看其中未包含Jettison的Older benchmarks我發現Kryo產生的文件較小,序列化和DeSerialized比一些替代方法更快。Jettison或Kryo

任何人都可以告訴我關鍵的區別或其他Jettison如何堆棧到Kryo,特別是對於未來的項目,如android應用程序。

編輯:

我想我在找什麼產生較小的文件和運行速度更快。人類可讀性可以犧牲,因爲我不上讀取文件只打算處理這些

回答

1

注:我是EclipseLink JAXB (MOXy)鉛和JAXB (JSR-222)專家小組的成員。

由於您已經建立了JAXB映射並將XML轉換爲JSON,因此您可能會對使用相同JAXB元數據提供對象到XML和對象到JSON映射的EclipseLink JAXB(MOXy)感興趣。

客戶

下面是JAXB註釋的樣本模型。

package forum11599191; 

import java.util.List; 
import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Customer { 

    @XmlAttribute 
    private int id; 

    private String firstName; 

    @XmlElement(nillable=true) 
    private String lastName; 

    private List<String> email; 

} 

jaxb.properties

要在同一個包中使用莫西爲您的JAXB提供你需要包括一個名爲jaxb.properties與以下條目您的域模型(見:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

input.xml中

<?xml version="1.0" encoding="UTF-8"?> 
<customer id="123" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <firstName>Jane</firstName> 
    <lastName xsi:nil="true"/> 
    <email>[email protected]</email> 
</customer> 

演示

下面演示代碼將填充從XML對象,然後輸出JSON。注意Moxy沒有編譯時間依賴性。

package forum11599191; 

import java.io.File; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Customer.class); 

     // Unmarshal from XML 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     File xml = new File("src/forum11599191/input.xml"); 
     Customer customer = (Customer) unmarshaller.unmarshal(xml); 

     // Marshal to JSON 
     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.setProperty("eclipselink.media-type", "application/json"); 
     marshaller.marshal(customer, System.out); 
    } 

} 

JSON輸出繼電器

下面是從運行演示代碼的輸出。

{ 
    "customer" : { 
     "id" : 123, 
     "firstName" : "Jane", 
     "lastName" : null, 
     "email" : [ "[email protected]" ] 
    } 
} 

有幾件事情需要注意的輸出:

  1. 由於id字段是數字型它編組到JSON沒有引號。
  2. 即使id字段已使用@XmlAttribute進行映射,但在JSON消息中沒有特別說明。
  3. email屬性的大小爲List,這在JSON輸出中正確表示。
  4. xsi:nil機制用於指定lastName字段有一個null值,這已被轉換爲JSON輸出中正確的空表示。

更多信息

+0

他們是一個導出混合HashMap列表的好方法嗎?即HashMap kdgwill 2012-09-01 17:25:46

3

他們是有所不同的用途:

  • 拋棄是讀/寫JSON。如果您需要使用JSON(人類可讀)數據格式進行交互,請使用它
  • Kryo用於高效的二進制序列化。如果您需要高性能和小編碼對象大小(例如實時遊戲中的消息通信),請使用它。

由於聽起來您正在使用該格式來存檔數據,因此人爲可讀性和使用標準的長時間格式可能比效率更重要,所以我懷疑您會希望選擇JSON路由。

+0

那麼這兩個項目實際上是遊戲這就是爲什麼KRYO吸引我。 – kdgwill 2012-07-22 14:37:45