[alibaba/fastjson]缺少默认构造函数导致无法反序列化

2023-12-15 535 views
3

Info类只有构造函数Info(String address),则无法反序列化admin字段,如果加上默认构造函数 public Info() { } 则可以反序列化admin字段

public class Issuexxxx extends TestCase {
    public void test_for_issue() throws Exception {
        String json = "{\"address\":\"1\",\"admin\":true}";
        Info info = JSON.parseObject(json, Info.class);
        assertTrue(info.isAdmin());
    }

    public class Info {
        private String address;
        private boolean admin;

        public Info(String address) {
            this.address = address;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public boolean isAdmin() {
            return admin;
        }

        public void setAdmin(boolean admin) {
            this.admin = admin;
        }
    }
}

回答

4

get/setter命名不规范,它序列化和反序列化的时候可能是按get/set+属性名去找对应方法的,只能说要不就idea一键生成或者lombok中注解给你生成算了

9

get/setter命名应该是规范的