杰克逊检查可选字段

时间:2018-09-28 13:13:14

标签: java json jackson jax-rs

问题

我正在JAX-RS项目中制作POJO(人员)并使用Jackson。
我想创建一个可选的String字段(例如此人居住的国家/地区),并能够检查其长度。

我的测试

通过参考本文(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 ),并指定 country ,例如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);
    }
}

2 个答案:

答案 0 :(得分:1)

问题

问题是我在国家/地区上输入了trim()(可能为NULL值)。参见下文:

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

解决方案

我要感谢@TheOddCoder的解决方案。我的@Pattern正则表达式没有更改,但是构造函数private Person(...) (@ JsonCreator)更改了以下内容:

@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();
    if(country == null) {
        this.country = country;
    } else {
        this.country = country.trim();
    }
}

答案 1 :(得分:0)

在您的情况下,我建议不要在字段中使用可选字段,而应验证您的国家(如果已设置)并以这种方式进行处理。

=substitute(substitute(rdata;"%price%";SheetProducts!C3); %productname%; SheetProducts!B3)

因此,您不必关心它是否已设置,并且无论什么正则表达式都将匹配。

我希望这会有所帮助。