spring - 如何忽略 Spring boot 中收入的特定字段?

标签 spring spring-boot jackson

我的领域类如下

@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 字段的方式配置序列化程序,所以我只得到 firstNamelastName,但在我将对象返回给调用者时对其进行序列化。

最佳答案

与 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/

相关文章:

java - 在 IntelliJ 15 中运行 Spring Boot MVC 时的路线 404

docker - docker容器内的多个spring boot

java - 有java注解列表吗?

java - 如何在 Spring boot 中从 Controller 覆盖 @JsonIninclude

java - 如果我有必填字段,则与 @JsonIgnoreProperties(ignoreUnknown = true) 相反?

java - Project Reactor如何并行调用两个或多个web服务或REST并加入答案

java - Gradle多模块项目的Spring平台bom

hibernate - $Proxy25 无法转换为我的类 Spring 框架

java - 类路径资源中定义的“springSecurityFilterChain”通过工厂方法实例化失败;

java - 使用 Jackson 解析 JSON 并提取嵌入类型