Search code examples
spring-mvcxstream

How to deserialize xml using XStream in spring mvc


Im receiving this

<header><h1>001</h1><h2>002</h2></header>

my dispatcher looks like this

<bean id="annotatedMarshaller" class="org.springframework.oxm.xstream.AnnotationXStreamMarshaller">
    <property name="annotatedClasses">
        <list>
        <value>someClasses</value>
        <value>someClasses</value>
        <value>someClasses</value>
        </list>
    </property>
</bean>

And here I try to use the unmarchal method from XstreamMarshaller and return the Object to cast

public static Object deserializeXml(String xml)  {


    StringReader sr =new StringReader(xml);
    StreamSource ss=new StreamSource(sr);

    Object o=null;
    try {

        o = xStreamMarshaller.unmarshal(ss);

    } catch (XmlMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    return o;
}

The problem came when I realized that the unmarshal method marshals the given object to a given javax.xml.transform.Result and not a simple String as the fromXml method from XStream.

thanks to THIS i figured out how to get a Result Object from a String, but not sure if is the best way to do it.


Solution

  • Totally agree with thought that spring should handle all marshaling/unmarshalling stuff. Everything you need is to declare XStreamMarshaller as one of message converters. That can be achieved via mvc:annotation section:

     <mvc:annotation-driven>
      <mvc:message-converters>
          <!-- Your XStream converter. -->
      </mvc:message-converters>
    </mvc:annotation-driven>
    

    or via AnnotationMethodHandlerAdapter:

     <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <!-- Your XStream converter. -->
                </list>
            </property>
        </bean>