Search code examples
javaencodingutf-8xstream

Xstream with special characters


I'm working with XStream but I have a problem with the special characters á,é,í,ó,ú and ñ.

I tried this:

  String charset = "UTF-8";
  xstream = new XStream(new DomDriver(charset));

(don't work)

I found that XStream does no character encoding by itself, it relies on the configuration of the underlying XML writer. By default it uses its own PrettyPrintWriter which writes into the default encoding of the current locale. To write UTF-8 you have to provide a Writer with the appropriate encoding yourself.

My problem is that I don't know how to provide a Writer...

// get the model from the map passed created by the controller
Object model = map.get("model");

Object viewData = transformViewData(model);

//TEST
Writer w = new OutputStreamWriter(viewData, "UTF-8");
//FINTEST

// if the model is null, we have an exception
String xml = null;
if (viewData != null){
    xml = xstream.toXML(viewData, w);  //Err:Cannot find symbol...
}else{
    // so render entire map
    xml = xstream.toXML(map, w); //Err:Cannot find symbol...
}

response.getOutputStream().write(xml.getBytes());

Solution

  • Finally, it's working !!!

    I fix it adding "UTF-8" in xml.getByte():

    response.getOutputStream().write(xml.getBytes("UTF-8"));