默认情况下,Moshi在序列化中会忽略空值,但是在某些情况下,我确实想使用空值来序列化对象,因此我尝试为这种情况创建@JsonQualifier,但最终结果是空值被忽略了。
如何在序列化(toJson)中忽略空值,但如何保留某些特定字段为空?
示例
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class KeepItNull
data class StackQuestion(val id : Int){
var question : String? = null
@KeepItNull
val answer : String? = null
}
响应应忽略“问题”并包含“答案”字段-像这样:
{
"id": 1,
"answer": null
}
答案 0 :(得分:1)
Jackson allows controlling this behavior at either the class level:
@JsonInclude(Include.NON_NULL)
public class MyDto { ... }
Or – more granularity – at the field level:
public class MyDto {
@JsonInclude(Include.NON_NULL)
private String stringValue;
private int intValue;
// standard getters and setters
}