marshaller将实体转为xml后里面的日期格式怎么设置

    Map<String, Object> map = new HashMap<>();
        Class<?> clazz = Class.forName(className);
        Object requestType=this.deserialize(jsonrequest, clazz);
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        Writer writer = new StringWriter();
        marshaller.marshal(requestType, writer);
        map.put("request", writer.toString());
        
        输出来的日期为        <Date>2019-06-30T00:00:00 08:00</Date>
        我希望输出的格式为  <Date>2019-06-30</Date>
阅读 449
评论 2019-06-17 提问
    1 个回答

    使用定制化的XmlAdapter加注解的方式。

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class DateAdapter extends XmlAdapter<String, Date> {
    
        // 简单版
    
        @Override
        public String marshal(Date v) throws Exception {
            synchronized (dateFormat) {
                return new SimpleDateFormat("yyyy-MM-dd");.format(v);
            }
        }
    
        @Override
        public Date unmarshal(String v) throws Exception {
            synchronized (dateFormat) {
                return new SimpleDateFormat("yyyy-MM-dd").format(v);
            }
        }
    
    }

    再在指定字段上使用@XmlJavaTypeAdapter注解,指定Adapter类

    @XmlElement(name = "timestamp", required = true) 
    @XmlJavaTypeAdapter(DateAdapter.class)
    protected Date timestamp; 
    评论 赞赏 2019-06-18
      撰写回答

      登录后参与交流、获取后续更新提醒