简体   繁体   中英

Public constructor for nested class

I'm parsing a JSON and bumped into an exception saying I don't have default constructor for one of my entities. Here is the code:

public class MyPromosResponse extends BaseResponse {

    public MyPromosResponseData response;

    public MyPromosResponse() {
    }

    public TreeSet<Promo> getMyPromosResponseData() {
        return new TreeSet<Promo>(response.getEvents());
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    class MyPromosResponseData {
        public ArrayList<Promo> events;
        public ArrayList<Table1PromoData> Table1;

        public MyPromosResponseData() {
        }

        public ArrayList<Promo> getEvents() {
            return events;
        }

        ArrayList<Table1PromoData> getTable1() {
            return Table1;
        }

    }

    class Table1PromoData {
        public int id;
        public int eventid;
        public int cardholderid;

        public Table1PromoData() { // Here is the constructor.
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getEventid() {
            return eventid;
        }

        public void setEventid(int eventid) {
            this.eventid = eventid;
        }

        public int getCardholderid() {
            return cardholderid;
        }

        public void setCardholderid(int cardholderid) {
            this.cardholderid = cardholderid;
        }
    }

}

When I have Table1PromoData as a nested class I have the error the default constructor can't be found, but there is a public constructor defined. If I move it to a separate file everything is fine - the lib finds the constructor.

Why the default constructor become visible after I moved it to a separate file?

Because inner classes can also be public, private, or protected. If you don't specify, its private and can't be seen outside the class. You need to declare the class as public.

如果我的内部类不是静态的,我遇到了JSON序列化程序(特别是Jackson)的问题 - 显然如果你的内部类不是静态的,那么默认构造函数会被破坏

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