我正在使用ToAttributedValueConverter
通过类注释:
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "text" })
public final class Message {
private final String text;
// Needed for XStream serialization
@SuppressWarnings("unused")
private Message() {
text = null;
}
public Message(final String text) {
if (text == null) {
throw new NullPointerException();
}
this.text = text;
}
public String getText() {
return this.text;
}
}
示例:
final XStream xstream = new XStream();
xstream.alias("message", Message.class);
xstream.processAnnotations(Message.class);
final Message message = new Message("Lorem Ipsum");
final String xml = xstream.toXML(message);
System.out.println(xml);
输出结果为:
<message>Lorem Ipsum</message>
为了将数据模型(类Message
)与持久性(XStream)分开,我将从数据模型中删除所有XStream注释。
例如,XStreamAlias("message")
可以简单地替换为xstream.alias("message", Message.class)
。
但是在xstream对象中替换ToAttributedValueConverter
是什么?
答案 0 :(得分:1)
有时答案很简单。
简短的回答是:使用xstream.registerConverter(converter)
答案很长:
ToAttributeValueConverter
是转换器。也就是说,您可以使用XStream实例注册该实例以影响序列化。
以下代码将在您的问题中执行您想要的操作,而不使用XStream批注(我将Message类用于该示例)。所有相关代码均采用main
方法:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
public class XmlSample {
public static void main(String[] args) {
XStream xStream = new XStream();
Converter converter = new ToAttributedValueConverter(Message.class,
xStream.getMapper(), xStream.getReflectionProvider(), xStream.getConverterLookup(), "text");
xStream.registerConverter(converter);
xStream.alias("message", Message.class);
System.out.println(xStream.toXML(new Message("testtest")));
}
public static final class Message {
private final String text;
// Needed for XStream serialization
@SuppressWarnings("unused")
private Message() {
text = null;
}
public Message(final String text) {
if (text == null) {
throw new NullPointerException();
}
this.text = text;
}
public String getText() {
return this.text;
}
}
}