科特林 - 杰克逊忽略了空值

时间:2017-08-03 08:01:44

标签: java jackson kotlin

我在使用Jackson解析JSON时遇到麻烦,我想忽略null属性。这是我的代码。

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ParsedSurvey(
    val items: List<ParsedSurveyItem> = listOf()
)

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ParsedSurveyItem(
    val type: String = "",
    val text: String = "",
    val instructions: String = "",
    val prog: String = "",
    val `var`: String = "",
    val columns: List<ParsedSurveyAnswer> = listOf(),
    val rows: List<ParsedSurveyAnswer> = listOf(),
    val num: String = "",
    val multi: Boolean = false,
    val random: Boolean = false,
    val min: Int = -1,
    val max: Int = -1,
    val recordOrder: Boolean = false,
    val rowLength: Int = -1
)

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ParsedSurveyAnswer @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) constructor(
    val text: String = "",
    val prog: String = "<p></p>",
    @JsonProperty("isOpen") val isOpen: Boolean = false
)

如果我尝试将ParsedSurveyItem中的rows属性设置为null。我收到了这个错误:

value failed for JSON property rows due to missing (therefore NULL) value for creator parameter rows which is a non-nullable type.
Jackson doesn't ignore 

杰克逊为何解析空值?谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

只有在行可为空的情况下才能设置rows属性null。它的意思是 将其更改为

 val rows: List<ParsedSurveyAnswer>? 

你也可以删除listOf()&amp; @JsonIgnoreProperties(ignoreUnknown = true)