我有以下 XStream 问题:当我尝试阅读注释时,我需要使用以下句子:
xstream.processAnnotations(DataClass .class);
它明确定义了我要序列化的类。但在我的代码中:
public class Tester {
/**
* @param args
*/
public static void main(String[] args) {
DataClass data = new DataClass();
data.familyName = "Pil";
data.firstName = "Paco";
data.ID = 33;
data.properties.put("one", "1");
data.properties.put("two", "2");
data.properties.put("three", "3");
String xml = getXmlString(data);
System.out.println(xml);
}
public static String getXmlString(Object data) {
String ret = "";
final StringWriter stringWriter = new StringWriter();
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(Object.class);
xstream.marshal(data, new PrettyPrintWriter(stringWriter));
ret = stringWriter.toString();
return ret;
}
}
其中 dataClass 是:
@XStreamAlias("data")
public class DataClass {
public Integer ID = 0;
public String firstName = "";
public String familyName = "";
public Map<String, String> properties = null;
public DataClass(){
properties = new HashMap<String,String>();
}
}
我想要这样的东西:
public static <T> String getXmlString(T data) {
String ret = "";
final StringWriter stringWriter = new StringWriter();
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(T.class);
xstream.marshal(data, new PrettyPrintWriter(stringWriter));
ret = stringWriter.toString();
return ret;
}
但它不起作用。
有谁知道我正在尝试做的事情是否可能?