I\'d like to serialise null for only one property in my JSON body that is going on a PUT. I don\'t want to serialize null for any other types in the object. Model class is l
Try approach from my gist:
https://gist.github.com/OleksandrKucherenko/ffb2126d37778b88fca3774f1666ce66
In my case I convert NULL from JSON into default double/integer value. You can easily modify the approach and make it work for your specific case.
p.s. its JAVA, convert it to Kotlin first.
Your toJson adapter method will return null when the qualified string value is null, and the JsonWriter will not write the null value.
Here is a qualifier and adapter factory to install that will work.
@Retention(RUNTIME)
@JsonQualifier
public @interface SerializeNulls {
JsonAdapter.Factory JSON_ADAPTER_FACTORY = new JsonAdapter.Factory() {
@Nullable @Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
Set<? extends Annotation> nextAnnotations =
Types.nextAnnotations(annotations, SerializeNulls.class);
if (nextAnnotations == null) {
return null;
}
return moshi.nextAdapter(this, type, nextAnnotations).serializeNulls();
}
};
}
Now, the following will pass.
class User(
var firstname: String?,
var lastname: String?,
@SerializeNulls var collegeInput: String?,
@SerializeNulls var otherCollege: String?
)
@Test fun serializeNullsQualifier() {
val moshi = Moshi.Builder()
.add(SerializeNulls.JSON_ADAPTER_FACTORY)
.add(KotlinJsonAdapterFactory())
.build()
val userAdapter = moshi.adapter(User::class.java)
val user = User(
firstname = "foo",
lastname = null,
collegeInput = "abcd",
otherCollege = null
)
assertThat(
userAdapter.toJson(user)
).isEqualTo(
"""{"firstname":"foo","collegeInput":"abcd","otherCollege":null}"""
)
}
Note that you should use the Kotlin support in Moshi to avoid the @field:
oddities.