使用 JAXB 编组 LocalDate [英] Marshalling LocalDate using JAXB

查看:41
本文介绍了使用 JAXB 编组 LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一系列链接类,我希望能够将其实例编组为 XML,以便我可以将它们保存到一个文件中,并在以后再次读取它们.

I'm building a series of linked classes whose instances I want to be able to marshall to XML so I can save them to a file and read them in again later.

目前我使用以下代码作为测试用例:

At present I'm using the following code as a test case:

import javax.xml.bind.annotation.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import java.time.LocalDate;

public class LocalDateExample
{
  @XmlRootElement
  private static class WrapperTest {
    public LocalDate startDate;
  }

  public static void main(String[] args) throws JAXBException
  {
    WrapperTest wt = new WrapperTest();
    LocalDate ld = LocalDate.of(2016, 3, 1);
    wt.startDate = ld;
    marshall(wt);
  }

  public static void marshall(Object jaxbObject) throws JAXBException
  {
    JAXBContext context = JAXBContext.newInstance(jaxbObject.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(jaxbObject, System.out);
  }
}

XML 输出为:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapperTest>
    <startDate/>
</wrapperTest>

startDate 元素为空是否有原因?我希望它包含日期的字符串表示(即 toString()).我是否需要自己编写一些代码才能做到这一点?

Is there a reason why the startDate element is empty? I would like it to contain the string representation of the date (i.e. toString()). Do I need to write some code of my own in order to do this?

java -version 的输出是:

openjdk version "1.8.0_66-internal"
OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode)

推荐答案

你必须像这样创建一个 XmlAdapter:

You will have to create an XmlAdapter like this:

public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
    public LocalDate unmarshal(String v) throws Exception {
        return LocalDate.parse(v);
    }

    public String marshal(LocalDate v) throws Exception {
        return v.toString();
    }
}

并使用

 @XmlJavaTypeAdapter(value = LocalDateAdapter.class)

如果您想在包级别定义适配器,另请参见 javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters.

See also javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters if you want to define your adapters on a package level.

这篇关于使用 JAXB 编组 LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆