【发布时间】:2019-10-23 03:08:57
【问题描述】:
我的问题似乎类似于GSON parse generic Json Array,但它似乎已经过时了旧的使用方式。我无法从中得到答案。
我正在解析一个带有 json 响应的 url,它返回一个数组
[{
"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=="
}]
得到
预期为 BEGIN_OBJECT,但在第 1 行第 2 列路径 $ 处为 BEGIN_ARRAY
并因此在应用程序启动时崩溃。 有我的方法:
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)
任何建议如何避免这种崩溃并正确解析它以使用字段?
【问题讨论】:
标签: android arrays json kotlin gson