Square MOSHI-如何将某些值序列化为null?

时间:2019-02-28 12:39:45

标签: android kotlin moshi json-serialization

默认情况下,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
}

1 个答案:

答案 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
}