@Data
@Builder
public class Student {
private Long id;
private String name;
private String teacherName;
private String className;
private String schoolName;
}
上面等价于
@Data
public class Student {
private Long id;
private String name;
private String teacherName;
private String className;
private String schoolName;
@Builder
public Student(Long id, String name, String teacherName, String className, String schoolName) {
this.id = id;
this.name = name;
this.teacherName = teacherName;
this.className = className;
this.schoolName = schoolName;
}
}
@Builder注解修饰类时,该类将没有无参构造方法
对于如下这种需要json字符串转换为实体类的情况,将报错
String studentJson = "{\"id\": 122456,\"name\": \"张三\",\"teacherName\": \"李四\",\"className\": \"高一\",\"schoolName\": \"一中\"}";
//将会报错com.alibaba.fastjson.JSONException: default constructor not found
Student student = JSON.parseObject(studentJson, new TypeReference<Student>(){});
System.out.println(JSON.toJSONString(student));
解决办法如下
第一种方法:Student加连个注解@NoArgsConstructor和@AllArgsConstructor
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Long id;
private String name;
private String teacherName;
private String className;
private String schoolName;
}
第二种方法:
@Data
public class Student {
private Long id;
private String name;
private String teacherName;
private String className;
private String schoolName;
@Builder
public Student() {
}
@Builder
public Student(Long id, String name, String teacherName, String className, String schoolName) {
this.id = id;
this.name = name;
this.teacherName = teacherName;
this.className = className;
this.schoolName = schoolName;
}
}
网友评论