I am having开发者_开发百科 an odd problem in a simple web service built with Spring 3 and MVC. The web service works ok and I get XML back just like I want, however, all the values for all Joda date/time types are empty.
So I have a UserDTO which is something like this:
@XmlRootElement(name = "user")
public class UserDTO
{
private String firstname;
private String lastname;
private LocalDate birthdate;
...
And I have a controller like:
@Controller
public class UserController
{
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public UserDTO getUser()
{
UserDTO userDTO = new UserDTO();
userDTO.setFirstname("Foo");
userDTO.setLastname("Bar");
userDTO.setBirthdate(new LocalDate(1980,1,1));
return userDTO;
}
}
I get the following XML back:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<firstname>Foo</firstname>
<lastname>Bar</lastname>
<birthdate />
</user>
If I change the 'Accept' header to application/json, I do get the date value
{"userVO":{"First Name","lastname":"Last Name","birthdate":[1978,12,5]}}
Any ideas on what this could be?
To answer my own question... the following link set me on the right path: http://bdoughan.blogspot.com/2011/05/jaxb-and-joda-time-dates-and-times.html
Basically you have to create an XmlAdapter for each type. Here is an example from the link:
package blog.jodatime;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;
public class DateTimeAdapter
extends XmlAdapter<String, DateTime>{
public DateTime unmarshal(String v) throws Exception {
return new DateTime(v);
}
public String marshal(DateTime v) throws Exception {
return v.toString();
}
}
精彩评论