mirror of
https://github.com/fankes/moshi.git
synced 2025-10-20 00:19:21 +08:00
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:
@@ -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
|
||||
|
@@ -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
|
||||
)
|
||||
|
@@ -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
|
||||
|
@@ -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()
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -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" })
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user