Moshi: Codegen not considering `@Json` annotation on superclass constructor parameters.

Created on 29 Sep 2018  Â·  6Comments  Â·  Source: square/moshi

abstract class Superclass(@Json(name="superclassPropertyJsonName") var superclassProperty: String? = null)

@JsonClass(generateAdapter = true)
class Subclass(@Json(name="subclassPropertyJsonName") val subclassProperty: String? = null) : Superclass()

@Test fun subclass() {
  val moshi = Moshi.Builder().build()
  val jsonAdapter = moshi.adapter(Subclass::class.java)

  val encoded = Subclass("hello").apply { superclassProperty = "world" }
  assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"subclassPropertyJsonName":"hello","superclassPropertyJsonName":"world"}""")

  val decoded = jsonAdapter.fromJson("""{"superclassPropertyJsonName":"world","subclassPropertyJsonName":"hello"}""")!!
  assertThat(decoded.subclassProperty).isEqualTo("hello")
  assertThat(decoded.superclassProperty).isEqualTo("world")
}

fails.

via https://github.com/square/moshi/issues/495#issuecomment-425401941

Most helpful comment

I think it’s cause @property:Json is visible to callers of subtypes; but the supertype constructor’s parameters are not.

All 6 comments

This is working as intended. This is because the subclass is explicitly initializing that value to it's default here: : Superclass().

marking the target as property makes the test case above pass.

abstract class Superclass(@property:Json(name="superclassPropertyJsonName") var superclassProperty: String? = null)

seems inconsistent?

At no point can Moshi call the superclass‘ constructor. It doesn't use it, and it cannot use it. But it can set properties.

right.
i'm confused and curious why @property:Json vs @Json makes a difference. I would have expected the @Json to be applied to the var property, without needing the explicit @property:Json.

I think it’s cause @property:Json is visible to callers of subtypes; but the supertype constructor’s parameters are not.

yeah! got it, thank you.

Was this page helpful?
0 / 5 - 0 ratings