我有同樣的問題時,我正在同春MVC 3和Jackson JSON處理器 ,最近,我遇到了同樣的問題與Spring MVC 3和工作JAXB用于XML序列化 。
讓我們來探討這個問題:
問題:
我有以下Java Bean,要使用Spring MVC 3以XML序列化:
package com.loiane.model;import java.util.Date;public class Company {private int id;private String company;private double price;private double change;private double pctChange;private Date lastChange;//getters and setters
我還有另一個對象將包裝上面的POJO:
package com.loiane.model;import java.util.List;import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="companies")
public class Companies {@XmlElement(required = true)private List<Company> list;public void setList(List<Company> list) {this.list = list;}
}
在我的Spring控制器中,我將通過@ResponseBody批注返回一個公司列表-這將使用JaxB自動序列化該對象:
@RequestMapping(value="/company/view.action")
public @ResponseBody Companies view() throws Exception {}
當我調用controller方法時,這就是它返回視圖的內容:
<companies><list><change>0.02</change><company>3m Co</company><id>1</id><lastChange>2011-09-01T00:00:00-03:00</lastChange><pctChange>0.03</pctChange><price>71.72</price></list><list><change>0.42</change><company>Alcoa Inc</company><id>2</id><lastChange>2011-09-01T00:00:00-03:00</lastChange><pctChange>1.47</pctChange><price>29.01</price></list>
</companies>
注意日期格式。 它不是我希望它返回的格式。 我需要以以下格式序列化日期:“ MM-dd-yyyy ” 解決方案:
我需要創建一個擴展XmlAdapter的類,并重寫marshal和unmarshal方法,在這些方法中,我將根據需要格式化日期:
package com.loiane.util;import java.text.SimpleDateFormat;
import java.util.Date;import javax.xml.bind.annotation.adapters.XmlAdapter;public class JaxbDateSerializer extends XmlAdapter<String, Date>{private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");@Overridepublic String marshal(Date date) throws Exception {return dateFormat.format(date);}@Overridepublic Date unmarshal(String date) throws Exception {return dateFormat.parse(date);}
}
在我的Java Bean類中,我只需要在date屬性的get方法中添加@XmlJavaTypeAdapter批注。
package com.loiane.model;import java.util.Date;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;import com.loiane.util.JaxbDateSerializer;public class Company {private int id;private String company;private double price;private double change;private double pctChange;private Date lastChange;@XmlJavaTypeAdapter(JaxbDateSerializer.class)public Date getLastChange() {return lastChange;}//getters and setters
}
如果我們嘗試再次調用controller方法,它將返回以下XML:
<companies><list><change>0.02</change><company>3m Co</company><id>1</id><lastChange>09-01-2011</lastChange><pctChange>0.03</pctChange><price>71.72</price></list><list><change>0.42</change><company>Alcoa Inc</company><id>2</id><lastChange>09-01-2011</lastChange><pctChange>1.47</pctChange><price>29.01</price></list>
</companies>
問題解決了!
編碼愉快!
參考:來自Loiane Groner博客博客的JCG合作伙伴 Loiane Groner提供的JAXB自定義綁定– Java.util.Date/Spring 3序列化 。
翻譯自: https://www.javacodegeeks.com/2012/06/jaxb-custom-binding-javautildate-spring.html