我的领域类如下
@Getter
@Setter
public class Student {
private Long id;
private String firstName;
private String lastName;
}
我有这个 Controller
@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);
}
}
现在我想要的是以忽略收入的 id
字段的方式配置序列化程序,所以我只得到 firstName
和 lastName
,但在我将对象返回给调用者时对其进行序列化。
最佳答案
与 jackson 一起使用很容易。有一个名为 @JsonProperty(access = Access.READ_ONLY)
的注解,您可以在其中定义该属性是应该取消还是序列化。只需将该注释放在您的 id
字段上即可。
@JsonProperty(access = Access.READ_ONLY)
private Long id;
Controller :
@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);
}
请求主体:
{
"id":1,
"firstName": "Patrick",
"lastName" : "secret"
}
toString() 的输出:
Student [id=null, firstName=Patrick, lastName=secret]
响应:
{
"id": 123,
"firstName": "Patrick",
"lastName": "secret"
}
附言如果您不发送 id 属性,它也会起作用:
{
"firstName": "Patrick",
"lastName" : "secret"
}
关于spring - 如何忽略 Spring boot 中收入的特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49314869/