0

在我的 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());
4

1 回答 1

1

您需要添加

@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

/edit,我现在的连接有限,但我记得你可以...

您将拥有您的 bean,该 bean 将用于与 xml 进行序列化

@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);

这有帮助吗?

于 2013-07-02T15:43:13.513 回答