Джексон ObjectMapper десериализовать универсальные типы - PullRequest
0 голосов
/ 30 июня 2019

В моем приложении для Android я использую Retrofit, и наш API соответствует формату JSONAPI: https://jsonapi.org

У меня есть эта функция в моем MyRepository для вызова API:

fun getData(userId: String) {
    webService.getData(userId)
        .enqueue(object : ApiResponseHandler<SomeModel>() {
            override fun onResponseOK(response: SomeModel) {
                // process response here
            }
        })
}

ApiResponseHandler.kt

open class ApiResponseHandler<T>() :Callback<JSONAPIDocument<T>> {
    override fun onResponse(call: Call<JSONAPIDocument<T>>, response: Response<JSONAPIDocument<T>>) {
        if (response.isSuccessful) {
            val body = response.body()
            body?.get()?.let {
                // process it here as T
                onResponseOK(it)
            }
        } else {
            response.errorBody()?.string()?.let { errorBodyStr ->
                // errorBodyStr here is a string that can be deserialized into JSONAPIDocument<T> (take note that its not T)
                val parentObject = ObjectMapper().readValue<JSONAPIDocument<T>>(jsonString, ???) // how to make the ::class.java here?
            }
        }
    }
}

Теперь его API возвращает успех, ответ отлично обрабатывается. Моя проблема, когда есть ошибки и ответная строка json возвращается в errorBody.

Проблема в том, как использовать Jackson ObjectMapper для десериализации всей строки json в JSONAPIDocument<T>. И конечная цель - получить объект как T

...