1

我正在使用 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 ......

谢谢!

4

1 回答 1

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

为你工作=)

于 2013-03-04T19:42:38.253 回答