我的春季启动应用程序中有两个Pojo

Pojo 1:FeedData

代码(我有get和set,只是这里没有显示):

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为空,对吗?

我的控制器代码:

@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);
    }

最佳答案

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

@Valid
private FeedDataJson feedDataJson;

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

07-24 09:25