在SimpleXML中序列化/取消序列化Java HashMap



在我的Java类中,我有一个属性:

private HashMap<String, Integer> keywordFrequencies;

我需要序列化/取消序列化相关类的对象。

SimpleXML可以表示这种类型的Java对象吗?XML可能是什么样子?

我的XML是这样的:

 <keywordFrequencies>
    <keyword key="Osborne">1</keyword>
    <keyword key="budget">3</keyword>
 </keywordFrequencies>

目前要取消序列化的代码是一种通用方法:

public static void printHashMap(HashMap<String, Integer> hm) {
    Set s = hm.entrySet();
    Iterator i = s.iterator();
    int j = 0;
    // Print the index.
    while(i.hasNext()) {
        Map.Entry m = (Map.Entry) i.next();
        System.out.println("No=" + (j + 1) + ", Key=" + m.getKey() + ", Freq=" + m.getValue());
        j++;
    }
}

Java类中的属性是:

@ElementMap(entry="keywordFrequencies", key="key", attribute=true, inline=true)
private HashMap<String, Integer> keywordFrequencies;

我调用的方法将哈希图打印为:

HashMap_Utils.printHashMap(requestOMDM.getKeywordFrequencies());

您需要添加

@ElementMap(entry="keywordFrequencies", key="key", attribute=true, inline=true)
private Map<String, Integer> keywordFrequencies;

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#map

/编辑,我现在的连接有限,但我记得你可以。。。

您将拥有用于序列化到xml 和从xml 序列化的bean

@Root(name="root")
public class Example {
   @Element
   private String someProperty;
   @ElementMap(entry="keywordFrequencies", key="key", attribute=true, inline=true)
   private Map<String, Integer> keywordFrequencies;
   // getters and setters ommited
}
Serializer serializer = new Persister();
Example ex = new Example();
// set properties of ex here...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.write(ex, baos); // you can put here a FileOutputStream("fileToWrite.xml") too
String content = new String(baos.getBytes(), "UTF-8");
System.out.println(content);
// and then to deserialize
Example retrievedFromXml = serializer.read(Example.class, content);

这有帮助吗?

最新更新