Search code examples
javaxmljsonxstream

How to disable pretty-printing(white space/newline) in XStream?


This is how I create XStream instance for XML:

XStream xstream = new XStream();

This is for JSON:

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

Both of them are pretty-printing (indenting) the output.

How can I ask the XStream to disable the pretty printing?


Solution

  • With some help from the community, I've figured out the answer.

    For XML you have to change the way how you serialize:

    The line:

    xStream.toXML(o, new OutputStreamWriter(stream, encoding));
    

    changed to line

    xStream.marshal(o, new CompactWriter(new OutputStreamWriter(stream, encoding)));
    

    For JSON you only change the way how the XStream is created. So the initialization of the XStream is changed to:

    private final XStream xstreamOut = new XStream(new JsonHierarchicalStreamDriver() {
        public HierarchicalStreamWriter createWriter(Writer writer) {
            return new JsonWriter(writer, new char[0], "", JsonWriter.DROP_ROOT_MODE);
        }
    });
    

    Note that the 4-parameter JsonWriter constructor is used.