简体   繁体   中英

Parsing API data which contain object (Klaxon) (Kotlin)

I have API response which contain object (graphic)

[
    {
        "code": 200,
        "status": "OK",
        "FirstDay": "2019-11-18",
        "LastDay": "2019-11-24",
        "graphic": {
            "2019-11-23": [
                {
                    "godzinaStart": "08:30",
                    "godzinaStop": "10:00",
                    "przedmiot": "Matematyka dyskretna",
                    "sala": "32AK8",
                    "nauczyciel": "xxx",
                    "grupy": "1K131; 1K132; 1K133; 1K134; 1K135; 2K131",
                    "typ": "wykład"
                },
            ],
            "2019-11-24": [
                {
                    "godzinaStart": "08:30",
                    "godzinaStop": "10:00",
                    "przedmiot": "Podstawy informatyki",
                    "sala": "308K",
                    "nauczyciel": "xxx",
                    "grupy": "1K131",
                    "typ": "laboratorium"
                },
            ]
        }
    }
]

I have to parse this JSON to object in Kotlin. So i made class with parameters

class GraphicAPIResponse(
    var code: Int,
    var status: String,
    var errorMessage: String = "",
    var FirstDay: String = "",
    var LastDay: String = "",
    var graphic: JsonObject? = null OR var graphic: JsonArray<Any>? = null (I tried both)
)

I'm parsing data by this function

val responeAPI = Klaxon().parseArray<GraphicAPIResponse>(response)

When graphic is JsonObiect type appliaction throw error

I/System.out: ERROR -> Unable to instantiate JsonObject with parameters []

When graphic is JsonArray<Any> type, here's error

I/System.out: ERROR -> Unable to instantiate GraphicAPIResponse with parameters [LastDay: 2019-11-24, code: 200, status: OK, graphic: java.lang.Object@aef265a, FirstDay: 2019-11-18]

I'm trying to resolve the problem from 2 hours. Can someone help me please? :(

@EDIT

Thank You @Alexey Romanov

That help

Define a type for the nested object:

class Lesson(val godzinaStart: String, val godzinaStop: String, ...)

and use it in GraphicAPIResponse :

class GraphicAPIResponse(
    var code: Int,
    var status: String,
    var errorMessage: String = "",
    var FirstDay: String = "",
    var LastDay: String = "",
    var graphic: Map<String, Lesson> = mapOf()
)

(though honestly, I'd expect JsonObject to work as well)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM