java 如何以编程方式更改默认的 JAXB 日期序列化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6378227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:39:49  来源:igfitidea点击:

How to change programmatically the default JAXB date serialization?

javaxmljaxb

提问by zhk

Is there a way to change the default way jaxb serialize/deserialize types, dates in my case, without specifying it through annotation and/or through xml jaxb binding as mentioned here http://jaxb.java.net/guide/Using_different_datatypes.html

有没有办法更改 jaxb 序列化/反序列化类型、日期的默认方式,而不是通过注释和/或通过 xml jaxb 绑定指定它,如这里提到的 http://jaxb.java.net/guide/Using_different_datatypes.html

I'd basically like to do something like:

我基本上想做类似的事情:

    JAXBContext jaxbContext = ...;
    Marshaller marshaller = jaxbContext.createMarshaller().setAdapter(new DateAdapter(dateFormat));

To have a preconfigured JaxBContext or Marshaller/Unmarshaller that serialize/deserialize dates in a customized way..

要有一个预配置的 JaxBContext 或 Marshaller/Unmarshaller 以自定义方式序列化/反序列化日期..

Couldn't find any resource that shows how to do expect through annotations or statically with the xml binding file.. Thanks!

找不到任何显示如何通过注释或静态使用 xml 绑定文件执行预期的资源..谢谢!

回答by Patrick Marchwiak

This isn't exactly what you're looking for but it beats annotating every Date field individually. You can set a XmlJavaTypeAdapter at the package level so that every reference to Date within your package will use it. If your objects are in the com.example package, you should add a package-info.java file to it with the following contents:

这并不完全是您要查找的内容,但它胜过单独注释每个日期字段。您可以在包级别设置 XmlJavaTypeAdapter,以便包中对 Date 的每个引用都将使用它。如果您的对象在 com.example 包中,您应该向其中添加一个 package-info.java 文件,其中包含以下内容:

@XmlJavaTypeAdapter(value=MyCustomDateAdapter.class,type=Date.class)
package com.example;

回答by chahuistle

Try this:

试试这个:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name = "event")
public class Event {

    private Date date;
    private String description;

    @XmlJavaTypeAdapter(DateFormatterAdapter.class)
    public Date getDate() {
        return date;
    }

    public void setDate(final Date date) {
        this.date = date;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    private static class DateFormatterAdapter extends XmlAdapter<String, Date> {
        private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd_mm_yyyy");

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

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

    public static void main(final String[] args) throws Exception {
        final JAXBContext context = JAXBContext.newInstance(Event.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final Event event = new Event();
        event.setDate(new Date());
        event.setDescription("im rick james");

        marshaller.marshal(event, System.out);
    }
}

This produces:

这产生:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<event>
    <date>16_05_2011</date>
    <description>im rick james</description>
</event>

回答by puppyDomminatedWorld

After searching whole jaxb documentation and many tutorials, I did not find any answer that can configure dates apart from what we hard code in XMLAdapter. I put a property file in classpath having date formats as for example: dateFormat=mm-dd-YYYY

在搜索了整个 jaxb 文档和许多教程之后,除了我们在 XMLAdapter 中硬编码的内容之外,我没有找到任何可以配置日期的答案。我在类路径中放置了一个具有日期格式的属性文件,例如:dateFormat=mm-dd-YYYY

Now your XMLAdapter implementation goes as below:

现在您的 XMLAdapter 实现如下:

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

public class ConfigurableAdapterForDate extends XmlAdapter<String, Date>{

    private static final String FORMAT = "yyyy-mm-dd";
    private String formatFromFile =  null;
    private SimpleDateFormat format = new SimpleDateFormat();

    private void setFormatFromFile() throws IOException {
        //load property file
        Properties prop = new Properties();
        InputStream is = this.getClass().getResourceAsStream("<path to your property file>");
        prop.load(is);

        //get the format from loaded property file
        formatFromFile = prop.getPropertyValue("dateFormat");

        if(formatFromFile != null) {
            format.applyPattern(formatFromFile);
        }
        else {
            format.applyPattern(FORMAT );
        }
    }

    @Override
    public Date unmarshal(String v) throws Exception {
        this.setFormatFromFile();
        return format.parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        this.setFormatFromFile();
        return format.format(v);
    }

}

Now you can use @XmlJavaTypeAdapter(ConfigurableAdapterForDate.class)for date objects which you want to serialize/deserialize. One is free to use spring also to load property file. Above code will configure your date accordingly.

现在您可以将 @XmlJavaTypeAdapter(ConfigurableAdapterForDate.class) 用于要序列化/反序列化的日期对象。一种是免费使用 spring 也可以加载属性文件。上面的代码将相应地配置您的日期。