moshi custom qualifier annotation to serialise null on one property only

前端 未结 2 1710
轻奢々
轻奢々 2021-01-18 16:24

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

相关标签:
2条回答
  • 2021-01-18 16:40

    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.

    0 讨论(0)
  • 2021-01-18 16:45

    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.

    0 讨论(0)
提交回复
热议问题