Car*_*ine 3 spring jackson spring-boot
我的域类如下
@Getter
@Setter
public class Student {
private Long id;
private String firstName;
private String lastName;
}
Run Code Online (Sandbox Code Playgroud)
我有这个控制器
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想要的是以忽略收入字段的方式配置序列化器id,因此我只得到firstName和lastName,但是当我将对象返回给调用者时对其进行序列化。
与 Jackson 一起使用很容易。有一个名为的注释@JsonProperty(access = Access.READ_ONLY),您可以在其中定义属性是否应该反序列化或序列化。只需将该注释放在您的id字段上即可。
@JsonProperty(access = Access.READ_ONLY)
private Long id;
Run Code Online (Sandbox Code Playgroud)
控制器:
@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);
}
Run Code Online (Sandbox Code Playgroud)
请求正文:
{
"id":1,
"firstName": "Patrick",
"lastName" : "secret"
}
Run Code Online (Sandbox Code Playgroud)
toString() 的输出:
Student [id=null, firstName=Patrick, lastName=secret]
Run Code Online (Sandbox Code Playgroud)
回复:
{
"id": 123,
"firstName": "Patrick",
"lastName": "secret"
}
Run Code Online (Sandbox Code Playgroud)
PS 如果您不发送 id 属性,它也将起作用:
{
"firstName": "Patrick",
"lastName" : "secret"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3351 次 |
| 最近记录: |