1

I'm doing serialization with XStream. For XML I use the StaxDriver and for JSON I use 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());
}

With XML I get pretty print, with JSON, I never get 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;
}

And if I leave my code this way, I will get XML instead of JSON, I had to rewrite my code this way to get JSON, but not pretty-printed:

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

Do you know a way to get pretty printing in JSON with the JettisonMappedXmlDriver?

In the XStream documentation there is no information about it, they even seem to find it OK:

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

but I cannot believe that there is no way to get pretty printed JSON using XStream if you want to be able to serialize and deserialize (JettisonMappedXmlDriver)...

Thanks!

facundofarias
  • 2,973
  • 28
  • 27
Rafa
  • 2,328
  • 3
  • 27
  • 44

1 Answers1

0

I once had a similar problem but i used JsonHierarchicalStreamDriver and my solution was

this.xstream = new XStream(new JsonHierarchicalStreamDriver () {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    }
});

So Maybe

this.xstream = new XStream(new JettisonMappedXmlDriver() {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    }
});

works for you =)

Wolfii
  • 355
  • 3
  • 9
  • Hi Wolfi, thank you for your answer, it is not really working and now I'm using GSON... – Rafa Mar 05 '13 at 12:38