我在使用 Spring 3 和 MVC 构建的简单 Web 服务中遇到了一个奇怪的问题。 Web 服务工作正常,我得到了我想要的 XML,但是,所有 Joda 日期/时间类型的所有值都是空的。
所以我有一个 UserDTO,它是这样的:
@XmlRootElement(name = "user")
public class UserDTO
{
private String firstname;
private String lastname;
private LocalDate birthdate;
...
我有一个像这样的 Controller :
@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;
}
}
我得到以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<firstname>Foo</firstname>
<lastname>Bar</lastname>
<birthdate />
</user>
如果我将“接受” header 更改为 application/json,我会得到日期值
{"userVO":{"名字","姓氏":"姓氏","生日":[1978,12,5]}}
关于这可能是什么有什么想法吗?
最佳答案
回答我自己的问题...以下链接让我走上了正确的道路:http://bdoughan.blogspot.com/2011/05/jaxb-and-joda-time-dates-and-times.html
基本上,您必须为每种类型创建一个 XmlAdapter。这是链接中的示例:
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();
}
}
关于java - 将 Spring 3、ReST 和 XML 与 Joda 日期类型一起使用时返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5985865/