How to marshall non-string objects with JAXB and Spring

Posted by lesula on Stack Overflow See other posts from Stack Overflow or by lesula
Published on 2012-10-07T22:12:17Z Indexed on 2012/10/08 9:37 UTC
Read the original article Hit count: 416

Filed under:
|
|
|

I was trying to follow this tutorial in order to create my own restful web-service using Spring framework. The client do a GET request to, let's say

http://api.myapp/app/students

and the server returns an xml version of the object classroom:

@XmlRootElement(name = "class")
    public class Classroom {

    private String classId = null;
    private ArrayList<Student> students = null;

    public Classroom() {
    }
    public String getClassId() {
        return classId;
    }
    public void setClassId(String classId) {
        this.classId = classId;
    }
    @XmlElement(name="student")
    public ArrayList<Student> getStudents() {
        return students;
    }
    public void setStudents(ArrayList<Student> students) {
        this.students = students;
    }
    }

The object Student is another bean containing only Strings.

In my app-servlet.xml i copied this lines:

<bean id="studentsView" class="org.springframework.web.servlet.view.xml.MarshallingView">
    <constructor-arg ref="jaxbMarshaller" />
</bean>

<!-- JAXB2 marshaller. Automagically turns beans into xml -->
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.spring.datasource.Classroom</value>
            <value>com.spring.datasource.Student</value>
        </list>
    </property>
</bean>

Now my question is: what if i wanted to insert some non-string objects as class variables? Let's say i want a tag containing the String version of an InetAddress, such as

<inetAddress>192.168.1.1</inetAddress>

How can i force JAXB to call the method inetAddress.toString() in such a way that it appears as a String in the xml? In the returned xml non-string objects are ignored!

© Stack Overflow or respective owner

Related posts about Xml

Related posts about spring