views:

32

answers:

1

I'm using Spring 3 to create some ReST services. When POSTing XML, Spring handles String fields but won't convert Date fields. Here is an example:

@XmlRootElement(name = "TestObj") 
@XmlAccessorType(XmlAccessType.FIELD)
public class TestObj {

    @XmlElement(type = Date.class, name = "Birthdate")
    @XmlJavaTypeAdapter(BirthdateXmlAdapter.class)
    private Date birthdate;

    @XmlElement(type = String.class, name = "Name")
    private String name;

    // getters and setters ...
}

I thought perhaps an XmlAdapter is required and created one to marshall/unmarshall according to the date format I need. BirthdateXmlAdapter is called but a null value is passed in which of course sets the birthdate field to null.

@RequestMapping(value="/test", method=RequestMethod.POST)
public TestObj test(@RequestBody TestObj testObj) {
    logger.debug(testObj.toString());

    return testObj;    
}

Pretty simple use case here. I use RestClient to POST XML and see the "name" attribute set properly in my TestObj but birthdate is null.

A: 

If you annotate as follows you:

import java.util.Date;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "TestObj")  
@XmlAccessorType(XmlAccessType.FIELD) 
public class TestObj { 

    @XmlElement(name = "Birthdate") 
    @XmlSchemaType(name="date")
    private Date birthdate; 

    @XmlElement(name = "Name") 
    private String name;

}

You can produce/consume the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TestObj>
    <Birthdate>2010-09-22</Birthdate>
    <Name>Jane Doe</Name>
</TestObj>
Blaise Doughan