使json请求对象中的属性不为null

z31licg0  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(269)

我正在构建一个spring应用程序 @RestController ,例如:

@RestController
@RequestMapping(value = "/master")
public class MyController {

    @Autowired
    private MyService service;

    @PostMapping("/call")
    public ResponseEntity<Boolean> apiCall(@RequestBody MyDTO myDto) { ;
        return new ResponseEntity<Boolean>(service.apiCall(myDto), OK);
    }

}

以及请求对象:

public class MyDTO {

    @JsonProperty("emp_number")
    private long empNumber;

    @JsonProperty("office_id")
    private long officeId;

    // ....constructors, etc.
}

在我想要的请求中 officeId 不为空。
到目前为止我已经试着在 officeId 字段为:

@com.fasterxml.jackson.databind.annotation.JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonProperty(required = true)
@javax.validation.constraints.NotNull

但在请求json中,即使我错过了 office_id ,它没有抛出任何错误。
我错过了什么?

bmvo0sr5

bmvo0sr51#

可能是在您的情况下,您正在反序列化请求,并且构造函数引用的缺少的原语属性被分配了一个默认值
java默认值
您可以尝试为mydto使用相应的长 Package 对象,而不是原语,或者为原语使用反序列化功能fail\u on \u null\u

atmip9wb

atmip9wb2#

必须将类型从primitive更改为wrapper,否则将考虑默认值0,验证将通过。
用注解mydto @Valid 注解。
当spring boot发现一个带有@valid注解的参数时,它会自动引导默认的jsr 380实现hibernate validator并验证该参数。
从这里开始
请将以下依赖项添加到pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

附言:我对回应结构做了一些小的调整,看看回应中的错误
整个代码如下:

package com.example.spring.java.springjavasamples;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class SpringJavaSamplesApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringJavaSamplesApplication.class, args);
    }

}

@RestController
@RequestMapping(value = "/master")
class MyController {

    private final MyService service;

    public MyController(MyService service) {
        this.service = service;
    }

    @PostMapping("/call")
    public ResponseEntity<Map<String, Object>> apiCall(@Valid @RequestBody MyDTO myDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            bindingResult.getAllErrors().forEach((error) -> {
                String fieldName = ((FieldError) error).getField();
                String errorMessage = error.getDefaultMessage();
                errors.put(fieldName, errorMessage);
            });
            return prepareResponse("error", errors, HttpStatus.BAD_REQUEST);
        } else {
            return prepareResponse("data", service.apiCall(myDto), HttpStatus.OK);
        }
    }

    private ResponseEntity<Map<String, Object>> prepareResponse(String key, Object data, HttpStatus status) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, data);
        return new ResponseEntity<>(map, status);
    }

}

class MyDTO {

    @NotNull(message = "Employee number cannot be null")
    @JsonProperty("emp_number")
    private Long empNumber;

    @NotNull(message = "Office Id cannot be null")
    @JsonProperty("office_id")
    private Long officeId;

    @Override
    public String toString() {
        return "MyDTO{" +
                "empNumber=" + empNumber +
                ", officeId=" + officeId +
                '}';
    }
}

@Service
class MyService {

    public String apiCall(MyDTO myDto) {
        System.out.println("all valid: " + myDto);
        return myDto.toString();
    }
}

相关问题