简体   繁体   English

Jaxb-列表元素的地图属性

[英]Jaxb - map attribute of list element

Hy, my xml looks like this: 嗨,我的xml看起来像这样:

<forecast>
 <time day="2014-06-02">
  <symbol></symbol>
 </time>
 <time day="2014-06-03">
  <symbol></symbol>
 </time>
</forecast>

I need map day attribute for each "time" object but it looks like it didn't work as I expect. 我需要每个“时间”对象的map day属性,但是它似乎没有按我预期的那样工作。

Heres my classes (java): 这是我的课程(java):

public class Forecast {
    @XmlElement
    public List<WeatherEvent> time;
}

public class WeatherEvent {
    @XmlAttribute(name = "day")
    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date day;
    @XmlElement
    public Symbol symbol;
}

public class DateAdapter extends XmlAdapter<String, Date> {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss");

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

    @Override
    public Date unmarshal(String v) throws Exception {
        Date date = dateFormat.parse(v);
        if (date == null) {
            SimpleDateFormat simplierFormat = new SimpleDateFormat("yyyy-MM-dd");
            date = simplierFormat.parse(v);
        }
        return date;
    }
}

How to map "day" attribute properly to make it not null? 如何正确映射“ day”属性以使其不为null?

The following line is going to throw a ParseException and exit the method and never get to the logic below when the date looks like: 2014-06-02 . 下面的行将引发ParseException并退出该方法,并且在日期如下时永远不会进入下面的逻辑: 2014-06-02

Date date = dateFormat.parse(v);

You will need to catch the exception and ignore it, and then apply the second formatter to it. 您将需要捕获该异常并将其忽略,然后将第二个格式化程序应用于该异常。

Date date = null;
try {
    Date date = dateFormat.parse(v);
} catch(ParseException e) {
    SimpleDateFormat simplierFormat = new SimpleDateFormat("yyyy-MM-dd");
    date = simplierFormat.parse(v);
}
return date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM