目前,Spring Boot示例应用程序正常创建。在请求中,如果有任何未知字段出现,那么我们需要抛出错误。
为此,正在使用@JsonIgnoreProperties(ignoreUnknown = false)
注释。但是,当我访问URL时,它无法正常工作。
请按以下方式查找代码段:
@RestController @RequestMapping(value = "/")
@JsonIgnoreProperties(ignoreUnknown = false) public class
UserController {
private final Logger LOG = LoggerFactory.getLogger(getClass());
private final UserRepository userRepository;
private final UserDAL userDAL;
public UserController(UserRepository userRepository, UserDAL userDAL){
this.userRepository = userRepository;
this.userDAL = userDAL;
}
@RequestMapping(
value = "/create", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public User addNewUsers(@RequestBody @Valid User user)
throws JsonProcessingException {
LOG.info("Saving user.");
CardInfo cardInfo = new CardInfo();
cardInfo.setCardId("12345678901");
user.setCardInfo(cardInfo);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(cardInfo);
user.setCardInfo1(jsonString);
userDAL.getAllUsers();
return userRepository.save(user);
}
请查看样本Pom如下: http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0
<groupId>com.journaldev.spring</groupId>
<artifactId>spring-boot-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-mongodb</name>
<description>Spring Boot MongoDB Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
答案 0 :(得分:3)
您至少有3个选项:
将@JsonIgnoreProperties
放在您反序列化的类上,而不是在Spring控制器中。
com.journaldev.bootifulmongodb.model.User
,所以很可能,您无法对其进行修改。配置ObjectMapper个实例:
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
Customize Spring Boot's Jackson Object Mapper - 通过设置正确的环境属性:
spring.jackson.deserialization.fail-上未知的属性=真
有关详细信息,请参阅section 76.3 of Spring Boot's reference。