我正在使用XStream进行序列化。对于XML,我使用StaxDriver,对于JSON,我使用JettisonMappedXmlDriver:
if (this.format == ISerializer.Format.JSON){
logger.info("json");
/* note: JsonHierarchicalStreamDriver can read Json only */
this.xstream = new XStream(new JettisonMappedXmlDriver());
}
else if (this.format == ISerializer.Format.XML){
logger.info("xml");
this.xstream = new XStream(new StaxDriver());
}
使用XML我得到漂亮的印刷品,使用JSON,我从来没有得到漂亮的印刷品:
public boolean toStream(Object object, Writer writer){
if(this.usePrettyPrint == true){
this.xstream.marshal(object, new PrettyPrintWriter(writer));
}else{
this.xstream.toXML(object, writer);
}
return true;
}
如果我以这种方式离开我的代码,我将获得XML而不是JSON,我不得不以这种方式重写我的代码来获取JSON,但不是很漂亮:
public boolean toStream(Object object, Writer writer){
if (this.format == ISerializer.Format.JSON){
this.xstream.toXML(object, writer);
}
else{
if(this.usePrettyPrint == true){
this.xstream.marshal(object, new PrettyPrintWriter(writer));
}else{
this.xstream.toXML(object, writer);
}
}
return true;
}
您是否知道使用JettisonMappedXmlDriver在JSON中进行漂亮打印的方法?
在XStream文档中没有关于它的信息,他们甚至似乎没有找到它:
http://x-stream.github.io/json-tutorial.html
但是如果你想能够序列化和反序列化(JettisonMappedXmlDriver),我无法相信没有办法使用XStream获得漂亮的JSON ......
谢谢!
答案 0 :(得分:0)
我曾遇到类似的问题,但我使用的是JsonHierarchicalStreamDriver,我的解决方案是
this.xstream = new XStream(new JsonHierarchicalStreamDriver () {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
所以也许
this.xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
适合你=)