2

By default, Moshi ignores null values in serialization, but in some case I DO want to serialize my object with null value, I've tried to create @JsonQualifier for this case, but in final result, null value was ignored.

How to ignore null values in serialization (toJson) but keep some specific field null ?

Example

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class KeepItNull


data class StackQuestion(val id : Int){
var question : String? = null

@KeepItNull
val answer : String? = null

}

Response should ignore 'question' and include 'answer' field - like this:

{
 "id": 1,
 "answer": null
}

1 Answers1

-7

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
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 1
    The question was specifically about Moshi. And while a lot of things are possible in Jackson, the same might not be equally true for Moshi. Also, switching may not be an option, as Jackson is significantly slower than Moshi for some large JSON objects. – user3738870 Mar 30 '20 at 14:51