Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何在春季启动时忽略收入的特定字段?_Spring_Spring Boot_Jackson - Fatal编程技术网

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"
}