views:

1336

answers:

3

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?

==== The Answer =====

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.

+1  A: 

Use the marschal method on xstream with a compact writer

xstream.marshal(someObject, new CompactWriter(out));
Mork0075
What is the difference between "marshal" and "toXML"?This is what I use now:xStream.toXML(o, new OutputStreamWriter(stream, encoding));
IgorM
Apparently the CompactWriter works only for XML. I've modified my command to the following one and now I'm getting always XML, even if I need JSON:xStream.marshal(o, new CompactWriter(new OutputStreamWriter(stream, encoding)));
IgorM
See JavaDoc - toXML: Serialize an object to a pretty-printed XML String. - marschal: Serialize and object to a hierarchical data structure (such as XML). So with marshal you get some output options. There doenst seam to be such an option for JSON.
Mork0075
A: 

See the answer in the body of the question. I've marked it as Wiki.

IgorM
+3  A: 

Thanks, your posts helped!!! Here is what I use to convert to a String.

String strXML = "";
XStream xs = new XStream();
StringWriter sw = new StringWriter();
xs.marshal(this,  new CompactWriter(sw));
strXML = sw.toString();

Keywords: java xstream string compactwriter

noclayto