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 like this
@Parcel
class User @ParcelConstructor constructor(var college: College?,
var firstname: String?,
var lastname: String?,
var email: String?,
var active: Boolean = true,
var updatedAt: String?,
var gender: String?,
var picture: String?,
var id: String?,
@field: [CollegeField] var collegeInput: String?,
@field: [CollegeField] var otherCollege: String?,)
I only want to serialise collegeInput and otherCollege fields if either of them are null. For example
val user = User(firstname = "foo", lastname=null, collegeInput="abcd", otherCollege = null)
Json will look something like this:
{"user":{
"firstname": "foo",
"collegeInput": "abcd",
"otherCollege": null
}}
Where otherCollege is null, lastname is omitted from the object as by default moshi does not serialise nulls which is what I want, but qualifer fields should be serialized with null values
I tried using
class UserAdapter {
@FromJson
@CollegeField
@Throws(Exception::class)
fun fromJson(reader: JsonReader): String? {
return when (reader.peek()) {
JsonReader.Token.NULL ->
reader.nextNull()
JsonReader.Token.STRING -> reader.nextString()
else -> {
reader.skipValue() // or throw
null
}
}
}
@ToJson
@Throws(IOException::class)
fun toJson(@CollegeField b: String?): String? {
return b
}
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class CollegeField
I added the adapter to moshi but it never gets called
@Provides
@Singleton
fun provideMoshi(): Moshi {
return Moshi.Builder()
.add(UserAdapter())
.build()
}
@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient, moshi: Moshi, apiConfig: ApiConfig): Retrofit {
return Retrofit.Builder()
.baseUrl(apiConfig.baseUrl)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…