How to marshal/unmarshal Java objects with private fields using JAXB

前端 未结 2 1679
小鲜肉
小鲜肉 2021-01-02 20:34

I know the basics of the JAXB API, but I am stuck with something I am trying to do, and I am not sure whether it is actually possible. Details are as follows:

I have

2条回答
  •  情深已故
    2021-01-02 20:59

    You should keep your fields private in any case. You have 2 options binding to fields

    1) annotate your fields with XmlElement or XmlAttribute annotation

    @XmlRootElement(name="book")
    public class Book {
        @XmlElement
        private String title;
        ...
    

    2) annotate your class with @XmlAccessorType(XmlAccessType.FIELD)

        @XmlRootElement(name="book")
        @XmlAccessorType(XmlAccessType.FIELD)
        public class Book {
             private String title;
             ...
    

提交回复
热议问题