做网站答辩总结范文,网站被k多久可以恢复,网站建设需要什么方案,电商网页设计理念jaxb utilJaxB可以处理Java.util.Date序列化#xff0c;但是需要以下格式#xff1a; “ yyyy-MM-ddTHH#xff1a;mm#xff1a;ss ”。 如果需要将日期对象格式化为另一种格式怎么办#xff1f; 我有同样的问题时#xff0c;我正在同春MVC 3和Jackson JSON处理器 … jaxb util JaxB可以处理Java.util.Date序列化但是需要以下格式 “ yyyy-MM-ddTHHmmss ”。 如果需要将日期对象格式化为另一种格式怎么办 我有同样的问题时我正在同春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(namecompanies)
public class Companies {XmlElement(required true)private ListCompany list;public void setList(ListCompany list) {this.list list;}
} 在我的Spring控制器中我将通过ResponseBody批注返回一个公司列表-这将使用JaxB自动序列化该对象 RequestMapping(value/company/view.action)
public ResponseBody Companies view() throws Exception {} 当我调用controller方法时这就是返回视图的内容 companieslistchange0.02/changecompany3m Co/companyid1/idlastChange2011-09-01T00:00:00-03:00/lastChangepctChange0.03/pctChangeprice71.72/price/listlistchange0.42/changecompanyAlcoa Inc/companyid2/idlastChange2011-09-01T00:00:00-03:00/lastChangepctChange1.47/pctChangeprice29.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 XmlAdapterString, 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 companieslistchange0.02/changecompany3m Co/companyid1/idlastChange09-01-2011/lastChangepctChange0.03/pctChangeprice71.72/price/listlistchange0.42/changecompanyAlcoa Inc/companyid2/idlastChange09-01-2011/lastChangepctChange1.47/pctChangeprice29.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.htmljaxb util