这就是我为XML创建XStream实例的方法:
XStream xstream = new XStream();
这适用于JSON:
private final XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
它们都是非常打印(缩进)输出。
如何让XStream禁用漂亮的打印?
答案 0 :(得分:19)
谢谢,你的帖子帮了!!!这是我用来转换为String的内容。
String strXML = "";
XStream xs = new XStream();
StringWriter sw = new StringWriter();
xs.marshal(this, new CompactWriter(sw));
strXML = sw.toString();
答案 1 :(得分:12)
在社区的帮助下,我找到了答案。
对于XML ,您必须更改序列化的方式:
该行:
xStream.toXML(o, new OutputStreamWriter(stream, encoding));
更改为行
xStream.marshal(o, new CompactWriter(new OutputStreamWriter(stream, encoding)));
对于JSON ,您只能更改XStream的创建方式。因此,XStream的初始化更改为:
private final XStream xstreamOut = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, new char[0], "", JsonWriter.DROP_ROOT_MODE);
}
});
请注意,使用了4参数JsonWriter构造函数。
答案 2 :(得分:4)
在xstream上使用紧凑编写器的marschal方法
xstream.marshal(someObject, new CompactWriter(out));
答案 3 :(得分:1)
漂亮打印的默认行为来自AbstractXmlDriver.createWriter()方法(XStream使用XppDriver作为其默认的分层流驱动程序,这扩展了AbstractXmlDriver):
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out, getNameCoder());
}
如果要全局禁用漂亮打印(同时保留所有其他默认行为)并且只使用简单的toXML(o)方法而不是使用此处建议的其他每个使用选项,那么可以将XStream实例初始化为如下。这改为使用CompactWriter覆盖上述方法。
XStream xstream = new XStream(new XppDriver() {
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
return new CompactWriter(out, getNameCoder());
}
});
答案 4 :(得分:0)
以这种方式创建XStream实例:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE, new JsonWriter.Format(new char[0], new char[0], 0));
}
});
这里是Format类的构造函数:
/**
* Create a new Formatter.
*
* @param lineIndenter the characters used for indenting the line
* @param newLine the characters used to create a new line
* @param mode the flags for the format modes
* @since 1.4
*/
public Format(char[] lineIndenter, char[] newLine, int mode) {
this(lineIndenter, newLine, mode, new NoNameCoder());
}
检查源代码JsonWriter
以获得更多信息
答案 5 :(得分:0)
这对我有用:
XStream stream = new XStream(new StaxDriver());
stream.toXML(messages, out);
StringWriter out = new StringWriter();
String s = out.toString();
LOG.info(s);