从Java Object获取JSON路径

时间:2017-08-18 16:59:00

标签: java json rest

如何获取特定字段的jsonpointer路径? 例如

{
    "name": "Test",
    "code": 101,
    "details": {
        "education": "UG",
        "age": 0
    }
}

如果任何一个字段有一些验证问题,我们需要在json指针表示法中发送错误“field”:“/ details / age”无效的细节。

示例错误消息

{
    "errors": [
       {
         "name": "VALIDATION_ERROR",
         "details": [
           {
             "field":"/details/age",
             "value": "",
             "issue": "Invalid Param::age",
             "location": "body"
           }
         ],
         "message": "Invalid data provided"
       }
     ]
 }

在验证请求对象时,如何获得JSONPointer表示法中的字段路径,如上所述。我们发送json请求,然后映射到对象下面。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "name", "code", "details" })
public class Example {

    @JsonProperty("name")
    private String name;
    @JsonProperty("code")
    private Integer code;
    @JsonProperty("details")
    private Details details;

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("code")
    public Integer getCode() {
        return code;
    }

    @JsonProperty("code")
    public void setCode(Integer code) {
        this.code = code;
    }

    @JsonProperty("details")
    public Details getDetails() {
        return details;
    }

    @JsonProperty("details")
    public void setDetails(Details details) {
        this.details = details;
    }

}


public class Details {

    @JsonProperty("education")
    private String education;
    @JsonProperty("age")
    private Integer age;

    @JsonProperty("education")
    public String getEducation() {
        return education;
    }

    @JsonProperty("education")
    public void setEducation(String education) {
        this.education = education;
    }

    @JsonProperty("age")
    public Integer getAge() {
        return age;
    }

    @JsonProperty("age")
    public void setAge(Integer age) {
        this.age = age;
    }

}

0 个答案:

没有答案