使用默认值从空类生成JSON

时间:2018-06-03 00:43:23

标签: java json jackson

现在我有一些课程......

@lombok.Data
public class Teacher {
    private String name;
    private Integer age;
    private List<Student> students;
}

@lombok.Date
public class Student {
    private String name;
    private Integer age;
}

是否有任何优雅方式可以使用默认值Teacher生成JSON,例如......

{
    "name" : "demoString",
    "age" : 99,
    "students" : [ {
        "name" : "demoString",
        "age" : 99
    } ]
}

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

在jackson中没有设置默认值的注释。您将需要通过空构造或直接属性赋值来实例化属性。

@lombok.Data
public class Teacher {
    private String name = "demoString";
    private Integer age = new Integer(99);
    private List<Student> students = Collections.singleton(new Student());
}

@lombok.Data
public class Student {
    private String name;
    private Integer age;
    public Student(){
     this.name = "demoString";
     this.age = new Integer(99);
    }
}