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

前端 未结 2 1656
小鲜肉
小鲜肉 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:51

    JAXB will need either: - A public instance variable Or - A private instance variable with public mutators and accessors.

    You will need mutators for marshalling and acessors for unmarshalling

    0 讨论(0)
  • 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;
             ...
    
    0 讨论(0)
提交回复
热议问题