gpt4 book ai didi

java - JettisonMappedXmlDriver 和 XStream 的 pretty-print

转载 作者:行者123 更新时间:2023-12-01 04:50:41 29 4
gpt4 key购买 nike

我正在使用 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,我得到 pretty-print ,使用 JSON,我永远不会得到 pretty-print :

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 中进行 pretty-print 吗?

在 XStream 文档中没有关于它的信息,他们甚至似乎认为它没问题:

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

但我不敢相信,如果您希望能够序列化和反序列化(JettisonMappedXmlDriver),则无法使用 XStream 获得 pretty-print JSON...

谢谢!

最佳答案

我曾经遇到过类似的问题,但我使用了 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);
}
});

适合你 =)

关于java - JettisonMappedXmlDriver 和 XStream 的 pretty-print ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15021132/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com