2011-12-13 38 views
0

所示,當我序列化一個類的對象以使得:Java序列與YAML(SnakeYaml庫),包含HashMap沒有在序列化輸出

class MyClass{ 

    String value; 
    public MyClass(){} 

    public void setValue(String value){ 
     this.value = value; 
    } 

    public String getValue(){ 
     return value; 
    } 

} 

和序列化它想:

MyClass c1 = new MyClass(); 
    c1.setValue("this is a value"); 
    Map<String, Object> result = new HashMap<String, Object>(); 

    result.put("MyClass", c1); 
    Yaml yaml = new Yaml(); 
    String output = yaml.dump(result); 

作品就好了。但是,現在如果在我的課,我有另一個值使得:

class MyClass{ 

    String value; 
    Map<Integer, AnotherClass> MyList 
    public MyClass(){} 

    public void setValue(String value){ 
     this.value = value; 
    } 

    Map<Integer, AnotherClass> CList = new HashMap<Integer, AnotherClass>(); 
    public void setList(AnotherClass AL){ 
     CList.put(1,AL); 
     this.MyList = CList; 
    } 

    public String getValue(){ 
     return value; 
    } 

} 

,現在我重複同樣的程序工作,但在串行輸出,我沒有看到這個HashMap中。什麼是問題,是否有一些不同的方法用於序列化HashMap類型的對象?請建議....

+0

請嘗試成爲[SSCCE](http://sscce.org/)。它會幫助你更快得到答案。 – edwardw

+0

@edwardw我不能再縮短它,否則沒有人會明白我想說的是什麼 – Johnydep

回答

0

地圖沒有吸氣劑,這就是爲什麼它被忽略。

+0

我沒有在代碼中顯示,但我同時擁有Map對象的getter和setter。但它只是被忽略,我不知道爲什麼? – Johnydep

+0

實際上現在我測試了其他自定義對象類型,如簡單的AnotherClass對象的getter和setter,但結果是一樣的。可能是YAML不考慮對象,我猜? – Johnydep

+0

獲得答案的最有效方法是編寫失敗的JUnit測試並在SnakeYAML中創建問題:http://code.google.com/p/snakeyaml/issues/list – Andrey