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

[BUG] Kotlin with snake case parsing from JSON #2961

Closed
catluc opened this issue May 21, 2019 · 2 comments
Closed

[BUG] Kotlin with snake case parsing from JSON #2961

catluc opened this issue May 21, 2019 · 2 comments

Comments

@catluc
Copy link

catluc commented May 21, 2019

Bug

A simple json as this one {cod_state_region: "whatever"}, moshi is not able to parse this String to the property in my class. i just read out on moshi, and the correct way to implement the mapping for snake_case and camel case in kotlin is to use the KotlinJsonAdapterFactory class.

At the moment of writing this i am on openapi-generator-maven-plugin V4.0.0 beta 3 and I tested the last release v4.0.0 and the problem is still the same

Description

My suggestion is to change the ApiClient mustache.
This method

protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
       if(body == null) {
           return null
       }
       val bodyContent = body.string()
       if (bodyContent.length == 0) {
           return null
       }
       return when(mediaType) {
           JsonMediaType -> Moshi.Builder().add(object {
                   @ToJson
                   fun toJson(uuid: UUID) = uuid.toString()
                   @FromJson
                   fun fromJson(s: String) = UUID.fromString(s)
               })
               //.add(ByteArrayAdapter())
               .build().adapter(T::class.java).fromJson(bodyContent)
           else ->  TODO("responseBody currently only supports JSON body.")
       }
   }

Into this method:

protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String = JsonMediaType): T? {
        if(body == null) return null
        return when(mediaType) {
            JsonMediaType -> Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                .build().adapter(T::class.java).fromJson(body.source())
            else -> TODO("responseBody currently only supports JSON body.")
        }
    }


@karismann
Copy link
Contributor

hello @catluc, could you please retry with latest snapshot version ? that should be fixed. Thanks.

@catluc
Copy link
Author

catluc commented May 24, 2019

just checked this commit: [Kotlin] Fix parse error when using custom field names with @JSON and it looks ok to me

@catluc catluc closed this as completed May 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants