Puchacz
Puchacz

Reputation: 2115

Jaxb - map attribute of list element

Hy, my xml looks like this:

<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.

Heres my classes (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?

Upvotes: 1

Views: 254

Answers (1)

bdoughan
bdoughan

Reputation: 149047

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.

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;

Upvotes: 1

Related Questions