gpt4 book ai didi

java - Spring Boot Pojo 的 Pojo 验证不起作用

转载 作者:行者123 更新时间:2023-12-02 08:42:31 25 4
gpt4 key购买 nike

我的 Spring Boot 应用程序中有两个 Pojo

Pojo 1:FeedData

代码(我有获取和设置,只是没有在这里显示):

package com.cms.tb.model;

import java.io.Serializable;

import javax.validation.constraints.NotBlank;

import com.fasterxml.jackson.annotation.JsonProperty;

public class FeedData implements Serializable{

@JsonProperty("feed_id")
private int feedId;

@JsonProperty("feed_category_id")
private int feedCategoryId;

@JsonProperty("feed_data_json")
private FeedDataJson feedDataJson;

@JsonProperty("user_profile")
private UserProfile userProfile;


}

..在上面的pojo中,还有另一个名为FeedDataJson的Pojo,它具有验证功能。

代码2:FeedDataJson Pojo

package com.cms.tb.model;

import java.util.List;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import com.fasterxml.jackson.annotation.JsonProperty;

public class FeedDataJson {

@NotBlank(message = "feed_title is Mandatory")
@Size(min = 4, max = 25, message
= "feed_title must be between 4 and 25 characters")
@JsonProperty("feed_title")
private String feedTitle;

@NotBlank(message = "feed_body is Mandatory")
@Size(min = 4, max = 2000, message
= "feed_body must be between 10 and 2000 characters")
@JsonProperty("feed_body")
private String feedBody;

@JsonProperty("feed_meta_tags")
private List<String> feedMetaTags;
}

每当我通过 POSTMAN 发送请求时,FeedDataJson Pojo 中都不会进行验证。

示例请求数据:

{
"feed_data_json":{
"feed_title":"",
"feed_body":"LOL",
"feed_meta_tags":["m1"]
},
"feed_category_id":1,
"user_profile":{
"user_id":1
}
}

这应该引发验证错误,因为 feed_title 为空,对吧?

我的 Controller 代码:

@PostMapping(path="/v1/createfeed")
public ResponseEntity<String> createFeedController(@Valid @RequestBody FeedData requestData)
throws TBFeedException, TBFeedDBException, JsonProcessingException {

// Create ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

String feedDataJson = mapper.writeValueAsString(requestData.getFeedDataJson());
FeedData newFeedInfo = ITBFeedDAO.createFeed(requestData,feedDataJson);
newFeedInfo.setFeedDataJson(requestData.getFeedDataJson());

JsonNode dataNode = mapper.valueToTree(newFeedInfo);

return new ResponseEntity<String>(generateResponse(dataNode), setHeaders(), HttpStatus.OK);
}

最佳答案

FeedData 类中的 feedDataJson 属性上使用 @Valid。

@Valid
private FeedDataJson feedDataJson;

对于嵌套属性,您还需要使用@Valid。

关于java - Spring Boot Pojo 的 Pojo 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com