如何忽略Spring启动时收入的具体字段?

时间:2018-03-16 06:59:27

标签: 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 = "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字段,因此我只获得firstNamelastName,但在我&#39时序列化它; m将对象返回给调用者。

1 个答案:

答案 0 :(得分:1)

它很容易与杰克逊一起使用。有一个名为@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);
}

请求人:

{
    "id":1,
    "firstName": "Patrick",
    "lastName" : "secret"
}

toString()的输出:

Student [id=null, firstName=Patrick, lastName=secret]

响应:

{
    "id": 123,
    "firstName": "Patrick",
    "lastName": "secret"
}

P.S。如果你不发送id属性它也会起作用:

{
    "firstName": "Patrick",
    "lastName" : "secret"
}