解析 xml 成 javaBean时 Date格式问题解决

    /**
     * xml转换成JavaBean
     * @param xml
     * @param c
     * @return
     */
    public static  T converyToBean(String xml, Class c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            logger.error("xml convert to javaBean err:",e);
        }

        return t;
    }

默认可以解析的 时间格式 为 2030-12-31T00:00:00

当时间格式为 2030-12-31 00:00:00 时 则解析不了

解决办法

创建解析类

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JaxbDateSerializer extends XmlAdapter {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String marshal(Date date) throws Exception {
        return dateFormat.format(date);
    }

    @Override
    public Date unmarshal(String date) throws Exception {
        return dateFormat.parse(date);
    }
}

添加 注解到 javaBean中属性的 get方法上

        @XmlJavaTypeAdapter(JaxbDateSerializer.class)
        public Date getCREATED() {
            return CREATED;
        }

        public void setCREATED(Date CREATED) {
            this.CREATED = CREATED;
        }

        public String getLAST_UPD_BY() {
            return LAST_UPD_BY;
        }

        public void setLAST_UPD_BY(String LAST_UPD_BY) {
            this.LAST_UPD_BY = LAST_UPD_BY;
        }
        @XmlJavaTypeAdapter(JaxbDateSerializer.class)
        public Date getLAST_UPD() {
            return LAST_UPD;
        }

        public void setLAST_UPD(Date LAST_UPD) {
            this.LAST_UPD = LAST_UPD;
        }

此时再次解析 xml 既可以成功解析了

    public static void main(String[] args) {

        String xml="" +
                "" +
                "HRHBDMJD_CUST_SALES_TEMPLATE" +
                "HAIERMDM" +
                "" +
                "2030-12-31 00:00:00" +
                "admin" +
                "2008-07-07 18:15:33" +
                "2019-01-15 15:32:10" +
                "" +
                "" +
                "";
                
        MdmResp pricebean=JaxbUtil.converyToBean(xml,MdmResp.class);

        System.out.println(pricebean);
    }

你可能感兴趣的:(WebService)