【发布时间】:2018-09-28 13:13:13
【问题描述】:
问题
我正在 JAX-RS 项目中制作 POJO(人)并使用 Jackson。
我想创建一个可选的字符串字段(例如该人居住的国家/地区)并能够检查其长度。
我的测试
通过参考这篇文章 (How to define optional json field using Jackson) 我知道如何创建一个可选字段。但是,如果我想用 javax.validation.constraints.Pattern 来检查它的长度,如下所示:
@Pattern(regexp = "(?:.{0,12})?")
private final String country;
国家不能为 NULL 或不再存在。
我尝试添加 @Optional (org.jvnet.hk2.annotations.Optional) 并指定 国家,例如 private final Optional<String> country;。这两种方法我都没有成功。
我的实际 POJO
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Pattern;
@JsonAutoDetect(creatorVisibility = Visibility.ANY, fieldVisibility = Visibility.ANY)
@JsonPropertyOrder({Person.LAST_NAME, Person.FIRST_NAME, Person.COUNTRY})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
/**
* The format string for the toString method
*/
private static final String TO_STRING_FORMAT = "%S %s %s";
/**
* JSON property name for the last name
*/
static final String LAST_NAME = "lastName";
/**
* JSON property name for the first name
*/
static final String FIRST_NAME = "firstName";
/**
* JSON property name for the country
*/
static final String COUNTRY = "country";
/**
* The last name of the person
*/
@NotBlank
private final String lastName;
/**
* The first name of the person
*/
@NotBlank
private final String firstName;
/**
* The country of the person
*/
@Pattern(regexp = "(?:.{0,12})?")
private final String country;
/**
* Returns an new {@code Person} with its properties initialized from parameters.
*
* @param lastName the last name of the person ({@link #lastName})
* @param firstName the first name of the person ({@link #firstName})
* @param country the country where the person live ({@link #country})
*/
// Only used by Jackson for the JSON data deserialization
@SuppressWarnings("unused")
@JsonCreator
private Person(@JsonProperty(Person.LAST_NAME) String lastName, @JsonProperty(Person.FIRST_NAME) String firstName, @JsonProperty(Person.COUNTRY) String country) {
this.lastName = lastName.trim();
this.firstName = firstName.trim();
this.country = country.trim();
}
/**
* Returns a new {@code Person} with its properties initialized from another one.
*
* @param person the instance used to create the new one
*/
Person(Person person) {
this.lastName = person.lastName;
this.firstName = person.firstName;
this.country = person.country;
}
/**
* Returns a textual representation of the {@code Person}: {@link #lastName} {@link #firstName} {@link #country}.
* <p>
* The {@code lastName} is converted to uppercase for better readability of the person's name.
*
* @return a string representation of the {@code Person}
*/
@Override
public String toString() {
return String.format(Person.TO_STRING_FORMAT, this.lastName, this.firstName, this.country);
}
}
【问题讨论】: