Fix @field:Json parameters annotations always taking precedence (#946)

* Add regression test for field json annotations

* Make json name null if absent rather than default to name

This fixes incorrect behavior where the parameter json name would always win out over the property value
This commit is contained in:
Zac Sweers
2019-10-05 21:26:43 -04:00
committed by GitHub
parent 9dc331f20c
commit dbed99d71b
5 changed files with 24 additions and 6 deletions

View File

@@ -26,7 +26,7 @@ internal class PropertyGenerator(
val isTransient: Boolean = false
) {
val name = target.name
val jsonName = target.jsonName
val jsonName = target.jsonName ?: target.name
val hasDefault = target.hasDefault
lateinit var localName: String

View File

@@ -22,6 +22,6 @@ internal data class TargetParameter(
val name: String,
val index: Int,
val hasDefault: Boolean,
val jsonName: String = name,
val jsonName: String? = null,
val qualifiers: Set<AnnotationSpec>? = null
)

View File

@@ -24,7 +24,7 @@ internal data class TargetProperty(
val propertySpec: PropertySpec,
val parameter: TargetParameter?,
val visibility: KModifier,
val jsonName: String
val jsonName: String?
) {
val name: String get() = propertySpec.name
val type: TypeName get() = propertySpec.type

View File

@@ -77,7 +77,7 @@ internal fun primaryConstructor(kotlinApi: TypeSpec, elements: Elements): Target
index = index,
hasDefault = parameter.defaultValue != null,
qualifiers = parameter.annotations.qualifiers(elements),
jsonName = parameter.annotations.jsonName() ?: name.escapeDollarSigns()
jsonName = parameter.annotations.jsonName()
)
}

View File

@@ -1126,14 +1126,32 @@ class GeneratedAdaptersTest {
}
@JsonClass(generateAdapter = true)
class InternalPropertyWithoutBackingField {
class InternalPropertyWithoutBackingField {
@Transient
private var foo: Int = 5
internal var bar
get() = foo
set(f) { foo = f}
set(f) {
foo = f
}
}
@JsonClass(generateAdapter = true)
data class ClassWithFieldJson(
@field:Json(name = "_links") val links: String
) {
@field:Json(name = "_ids") var ids: String? = null
}
// Regression test to ensure annotations with field site targets still use the right name
@Test fun classWithFieldJsonTargets() {
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter<ClassWithFieldJson>()
//language=JSON
val instance = adapter.fromJson("""{"_links": "link", "_ids": "id" }""")!!
assertThat(instance).isEqualTo(ClassWithFieldJson("link").apply { ids = "id" })
}
}