JSON杰克逊创建者:默认值,很高兴有价值

时间:2014-10-28 10:40:36

标签: java json jackson

我必须构建一个带有必填字段的json,默认字段(如果未设置值)和可选(非强制)字段。此类用于取消和序列化。最终的json应该看起来不同,例如某些非强制字段未设置或未设置强制值,但应默认。

@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown=true)
public class TryoutJson {

    @JsonCreator
    public TryoutJson(
        @NotBlank
        @JsonProperty("mandatory")
        final String mandatory,
        @...WHAT HERE TO set to default?
        @JsonProperty("valueDefaultedTo5IfNotSet")
        final String valueDefaultedTo5IfNotSet,
        @... What here to set just if value is given?
        @JsonProperty("thisFieldIsNotMAndatory")
        final String thisFieldIsNotMAndatory,
    ) throws IllegalArgumentException
    {
     //....
    }

}

例如,应在使用的构造函数中创建此json字符串:

{"mandatory":"mandatoryValue","valueDefaultedTo5IfNotSet":"5"} is the same like {"mandatory":"mandatoryValue"}

{"mandatory":"mandatoryValue","valueDefaultedTo5IfNotSet":"2","thisFieldIsNotMAndatory":"ValueXY"}

是否可以只为所有这些设置使用一个构造函数?我不想为每个可能的变体构建几个构造函数。 如果重要,则使用此导入:

import org.hibernate.validator.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

0 个答案:

没有答案