2013-02-22 155 views
1

我正在用XStream进行序列化。对于XML我使用StaxDriver和JSON我使用JettisonMappedXmlDriver:JettisonMappedXmlDriver和漂亮的XStream打印

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; 
} 

你知道一种方式来获得漂亮的打印在JSON与JettisonMappedXmlD河?

在XStream的文档没有关于它的信息,他们甚至似乎觉得OK:

http://x-stream.github.io/json-tutorial.html

,但我不能相信,有没有办法让漂亮打印JSON,如果你使用的XStream希望能够序列化和反序列化(JettisonMappedXmlDriver)...

谢谢!

回答

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

作品你=)

+0

Wolfi你好,谢谢你的回答,它不是真的工作,现在我正在使用GSON ... – Rafa 2013-03-05 12:38:12