Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get SerialName value? #1482

Closed
P1NG2WIN opened this issue May 14, 2021 · 2 comments
Closed

Get SerialName value? #1482

P1NG2WIN opened this issue May 14, 2021 · 2 comments
Labels

Comments

@P1NG2WIN
Copy link

How can I get the SerialName annotation value in code?

With gson i use that extensions but after change SerializedName to SerialName they return null

fun KProperty<*>.serializedName(): String? {
    return javaField
        ?.getAnnotation(SerializedName::class.java)
        ?.value
}

fun KProperty<*>.serializedName(defaultValue: String): String {
    return javaField
        ?.getAnnotation(SerializedName::class.java)
        ?.value ?: defaultValue
}
@P1NG2WIN
Copy link
Author

fixed functions. Now all works

fun KProperty<*>.serializedName() =
    (annotations.find { it is SerialName } as? SerialName)
        ?.value

fun KProperty<*>.serializedName(defaultValue: String) =
    (annotations.find { it is SerialName } as? SerialName)
        ?.value ?: defaultValue

Is there a way to get value without reflection?

@sandwwraith
Copy link
Member

sandwwraith commented May 14, 2021

Property serial name is stored in corresponding class' SerialDescriptor. Try this example: Pair.serializer().descriptor.elementNames.toList(). Also check out getElementName/getElementIndex

sschuberth added a commit to oss-review-toolkit/ort that referenced this issue May 27, 2024
Based on the hint at [1] and the code at [2], leverage the serializer's
descriptor to get the serial name of the element, without doing any
"dummy serialization".

[1]: Kotlin/kotlinx.serialization#1482 (comment)
[2]: https://github.com/andregasser/bigbone/pull/332/files#diff-8d64fdf06ceb51ff99e649f64c911cf787b07aff678d5d7efd7bf13322db4983R90

Signed-off-by: Sebastian Schuberth <sebastian@doubleopen.org>
sschuberth added a commit to oss-review-toolkit/ort that referenced this issue May 27, 2024
Based on the hint at [1] and the code at [2], leverage the serializer's
descriptor to get the serial name of the element, without doing any
"dummy serialization".

[1]: Kotlin/kotlinx.serialization#1482 (comment)
[2]: https://github.com/andregasser/bigbone/pull/332/files#diff-8d64fdf06ceb51ff99e649f64c911cf787b07aff678d5d7efd7bf13322db4983R90

Signed-off-by: Sebastian Schuberth <sebastian@doubleopen.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants