我想用KON使用GSON对json进行反序列化。但它返回Null。 Json从对象开始。
这是Json
val json = """{
"05-04-2018": [
{
"start_datetime": "2018-04-05 20:00:00",
"event_id": "1",
"event_title": "Anna Karenina",
"city_id": "1",
"stage_name": "Cüneyt Gökçer Sahnesi",
"address": "Çayyolu Ankara"
}
],
"07-04-2018": [
{
"start_datetime": "2018-04-07 15:00:00",
"event_id": "1",
"event_title": "Anna Karenina",
"city_id": "1",
"stage_name": "Cüneyt Gökçer Sahnesi",
"address": "Çayyolu Ankara"
},
{
"start_datetime": "2018-04-07 20:00:00",
"event_id": "1",
"event_title": "Anna Karenina",
"city_id": "1",
"stage_name": "Cüneyt Gökçer Sahnesi",
"address": "Çayyolu Ankara"
}
]
}"""
包含事件列表的类。另一个是项目类别。
data class Event (val event_id: Int,val event_title: String, val event_stage: String, val event_posterUri: String, val event_starttime: String)
data class EventArray (val dates: String, val eventArrayList: ArrayList<Event>)
和GSON部分
val sadasd: EventArray = gson.fromJson(json, EventArray::class.java)
答案 0 :(得分:0)
请重试这些数据类:
data class EventArray(
val `05-04-2018`: List<Event>,
val `07-04-2018`: List<Event>
)
data class Event(
val start_datetime: String,
val event_id: String,
val event_title: String,
val city_id: String,
val stage_name: String,
val address: String
)
使用这些数据类,我运行println(Gson().fromJson(json, EventArray::class.java))
并获取:
EventArray(05-04-2018=[Event(start_datetime=2018-04-05 20:00:00, event_id=1, event_title=Anna Karenina, city_id=1, stage_name=Cüneyt Gökçer Sahnesi, address=Çayyolu Ankara)], 07-04-2018=[Event(start_datetime=2018-04-07 15:00:00, event_id=1, event_title=Anna Karenina, city_id=1, stage_name=Cüneyt Gökçer Sahnesi, address=Çayyolu Ankara), Event(start_datetime=2018-04-07 20:00:00, event_id=1, event_title=Anna Karenina, city_id=1, stage_name=Cüneyt Gökçer Sahnesi, address=Çayyolu Ankara)])
答案 1 :(得分:0)
所以我理解日期是动态的。如果您无法更改API设计,这是一种方法。
使用JsonParser
解析JSON,如下所示:
val parsedJson = JsonParser().parse(json).asJsonObject
从此
中提取密钥val keys = parsedJson.keySet();
遍历键,将内容提取为JsonArray
,然后迭代每个键并将其映射到类。
for (key in keys) {
var eventArray = parsedJson[key].asJsonArray
eventArray.forEach {
val event = Gson().fromJson(it.asJsonObject, Event::class.java)
print(event)
}
}
理想情况下,您希望开始使用更好的JSON。