简体   繁体   English

JAXB XmlElement Annotation从String转换为int

[英]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. 我通过Web服务接收XML,并且我使用XmlElement Annotation将XML解析为Java。 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. 我对int领域特别感兴趣。 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). 我看到很多类似于@XmlElement的例子(name =“something”type = Integer.class)。 Is this type attribute also advised on the XmlJavaTypeAdapter annotation? 是否也在XmlJavaTypeAdapter注释上建议了此类型属性? 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. 我为一长串问题道歉,这是我第一次使用XmlElement注释,我想确保我做得对。 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)). 但是,如果Age元素可能包含null ,则可能需要用Integer替换int (您应该在XSD文件中检查Person元素的定义(如果它是Web服务,您可以在wsdl文件中找到xsd))。

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

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