Spring 如何在春季启动时忽略收入的特定字段?
我的域类如下Spring 如何在春季启动时忽略收入的特定字段?,spring,spring-boot,jackson,Spring,Spring Boot,Jackson,我的域类如下 @Getter @Setter public class Student { private Long id; private String firstName; private String lastName; } 我有一个控制器 @RestController @RequestMapping("/student") public class StudentController { @PostMapping(consumes = "appl
@Getter
@Setter
public class Student {
private Long id;
private String firstName;
private String lastName;
}
我有一个控制器
@RestController
@RequestMapping("/student")
public class StudentController {
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<Student> post(@RequestBody Student student) {
//todo save student info in db, it get's an auto-generated id
return new ResponseEntity<>(student, HttpStatus.CREATED);
}
}
@RestController
@请求映射(“/student”)
公共班级学生控制员{
@后期映射(consumes=“application/json”,products=“application/json”)
公共响应帖子(@RequestBody-Student){
//要在db中保存学生信息,它是一个自动生成的id
返回新的ResponseEntity(student,HttpStatus.CREATED);
}
}
现在,我想配置序列化程序,使其忽略income上的
id
字段,因此我只获得firstName
和lastName
,但在将对象返回给调用方时将其序列化。与jackson一起使用很容易。有一个名为@JsonProperty(access=access.READ_ONLY)
的注释,您可以在其中定义该属性是反序列化还是序列化。只需在id
字段中添加注释即可
@JsonProperty(access = Access.READ_ONLY)
private Long id;
控制员:
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<Student> post(@RequestBody Student student) {
//here we will see the that id is not deserialized
System.out.println(student.toString());
//here we set a new Id to the student.
student.setId(123L);
//in the response we will see that student will serialized with an id.
return new ResponseEntity<>(student, HttpStatus.CREATED);
}
toString()的输出:
答复:
{
"id": 123,
"firstName": "Patrick",
"lastName": "secret"
}
另外,如果您不发送id属性,它也会起作用:
{
"firstName": "Patrick",
"lastName" : "secret"
}
{
"id": 123,
"firstName": "Patrick",
"lastName": "secret"
}
{
"firstName": "Patrick",
"lastName" : "secret"
}