kotlin - moshi自定义限定符批注仅在一个属性上序列化null

标签 kotlin gson retrofit moshi

我只想对要进行PUT的JSON正文中的一个属性序列化null。我不想为对象中的任何其他类型序列化null。模型课是这样的

@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?,)

如果它们中的任何一个为null,我只想序列化collegeInput和otherCollege字段。例如
val user = User(firstname = "foo", lastname=null, collegeInput="abcd", otherCollege = null)

杰森看起来像这样:
{"user":{
  "firstname": "foo",
  "collegeInput": "abcd",
  "otherCollege": null
}}

在otherCollege为null的情况下,对象将省略姓氏,因为默认情况下,moshi不会序列化我想要的null,但是应将qualifer字段序列化为null值

我尝试使用
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

我将适配器添加到了moshi,但是它从未被调用过
@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()
}

最佳答案

当限定的字符串值为null时,您的toJson适配器方法将返回null,并且JsonWriter不会写入该null值。

这是要安装的限定符和适配器工厂。

@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();
    }
  };
}

现在,以下将通过。
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}"""
  )
}

请注意,您应该使用Kotlin support in Moshi来避免@field:的怪异之处。

关于kotlin - moshi自定义限定符批注仅在一个属性上序列化null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254876/

相关文章:

java - 为 mingw/ios/linus/其他源集导入 java lib 的解决方法?

java - 将具有不同键类型的映射序列化为 json

Java GSON : Getting the list of all keys under a JSONObject

java - Android自定义RxJava多次调用

java - SimpleXML with Retrofit 1.9, 'Attribute ' 版本'在类中没有匹配项'

java - Spring Facebook 模板将 fetchObject 映射到 PagedList

android - Kotlin 抽象类二级构造函数

java - 使用 GSON 反序列化嵌套对象

java - 改造 2.0 : getting response code 200 but not getting the desired data

kotlin - 我该如何解决这个错误 "Kotlin: [Internal Error] java.lang.ExceptionInInitializerError"