简体   繁体   中英

JAXB XmlElement Annotation convert from String to int

I am receiving XML via a web service, and I am parsing the XML into Java using the XmlElement Annotation. Here is how I am using the annotations. Please let me know if I am using them correctly. I am particularly interested in the int field. It seems to be working, but I feel like I am not using the annotations correctly. I see a lot of examples similar to @XmlElement(name="something" type=Integer.class). Is this type attribute also advised on the XmlJavaTypeAdapter annotation? I apologize for the long list of questions, this is my first time using the XmlElement annotations, and I want to make sure I'm doing it right. Thank you in advance for any help.

@XmlRootElement(name="Person")
public class Person {
    @XmlElement(name="FirstName")
    public String firstName = "";

    @XmlElement(name="LastName")
    public String lastName="";

    @XmlElement(name="Age")
    public int age = 0;

    @XmlElement(name="BirthDate")
    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date birthDate = new Date(0);
}


public class DateAdapter extends XmlAdapter<String, Date> {
    private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public String marshal(Date date) throws Exception {
        return (date == null) ? "" : FORMAT.format(date);
    }

    @Override
    public Date unmarshal(String str) throws Exception {
        return FORMAT.parse(str);
    }
}

In my opinion your solution is correct.

However, you may need to replace int with Integer if the Age element may contain null (you should check Person element's definition in the XSD file (if it is a web service you can find the xsd in the wsdl file)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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