Yevhen_Radchenko
Yevhen_Radchenko

Reputation: 1175

(Kotlin) GSON incorrect response parsing from json array

My problem seems similar to GSON parse generic Json Array but it seems outdated to old way of usage. And I can't get an answer from it.

Im parsing an url with json response, which is returning an array

[{
    "flight_number": 1,
    "mission_name": "FalconSat",
    "mission_id": [],
    "upcoming": false,
    "launch_year": "2006",
    "launch_date_unix": 1143239400,
    "launch_date_utc": "2006-03-24T22:30:00.000Z",
    "launch_date_local": "2006-03-25T10:30:00+12:00",
    "is_tentative": false,
    "tentative_max_precision": "hour",
    "tbd": false,
    "launch_window": 0,
    "rocket": {
        "rocket_id": "falcon1",
        "rocket_name": "Falcon 1",
        "rocket_type": "Merlin A",
        "first_stage": {
            "cores": [{
                "core_serial": "Merlin1A",
                "flight": 1,
                "block": null,
                "gridfins": false,
                "legs": false,
                "reused": false,
                "land_success": null,
                "landing_intent": false,
                "landing_type": null,
                "landing_vehicle": null
            }]
        },
        "second_stage": {
            "block": 1,
            "payloads": [{
                "payload_id": "FalconSAT-2",
                "norad_id": [],
                "reused": false,
                "customers": ["DARPA"],
                "nationality": "United States",
                "manufacturer": "SSTL",
                "payload_type": "Satellite",
                "payload_mass_kg": 20,
                "payload_mass_lbs": 43,
                "orbit": "LEO",
                "orbit_params": {
                    "reference_system": "geocentric",
                    "regime": "low-earth",
                    "longitude": null,
                    "semi_major_axis_km": null,
                    "eccentricity": null,
                    "periapsis_km": 400,
                    "apoapsis_km": 500,
                    "inclination_deg": 39,
                    "period_min": null,
                    "lifespan_years": null,
                    "epoch": null,
                    "mean_motion": null,
                    "raan": null,
                    "arg_of_pericenter": null,
                    "mean_anomaly": null
                },
                "uid": "UerI6qmZTU2Fx2efDFm3QQ=="
            }]

And getting

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

And crash on the start of the app as a result. There is my method:

val url = "https://api.spacexdata.com/v3/launches"
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()
                println(body)

                val gson = GsonBuilder().create()

                val spaceXFeed = gson.fromJson(body, SpaceXFeed::class.java)
            }

            override fun onFailure(call: Call, e: IOException) {
                println("Failed to execute request")
            }
        })

    }
}

class SpaceXFeed(val images: List<Images>)

class Images(val id: Int, val name: String)

Any advices how to avoid this crash and parse it properly to use fields ?

Upvotes: 0

Views: 1614

Answers (1)

Duy Khanh Nguyen
Duy Khanh Nguyen

Reputation: 509

Your json string is an array of objects, so that you need to parse it with a list/array type

val listType = object : TypeToken<List<Your_Object>>() { }.type
val spaceXFeed = gson.fromJson<List<Your_Object>>(body, listType)

Upvotes: 1

Related Questions