英文:
Transform multiple properties of the same type to List of these properties in data class Kotlin
问题
在我的应用程序中,我从JSON中检索数据,不幸的是,它的格式不允许我直接获得一个列表。如何将我的数据类转换为只包含一个属性:List< Itinerary >,其中包含这10个(或更多)行程?
data class ItineraryData(
val itineraries: List<Itinerary>
)
JSON数据
"itinerary_data" : {
"itinerary_0": {...},
"itinerary_1": {...},
"itinerary_2": {...},
"itinerary_3": {...},
"itinerary_4": {...},
"itinerary_5": {...},
"itinerary_6": {...},
"itinerary_7": {...},
"itinerary_8": {...},
"itinerary_9": {...}
}
英文:
In my app I'm retrieving data from json and unfortunately, It is written in such a way, that I can't straight away obtain a list. How can I transform my data class to consist of one property: List< Itinerary > which consists these 10 (or more) itineraries?
data class ItineraryData(
val itinerary0: Itinerary,
val itinerary1: Itinerary,
val itinerary2: Itinerary,
val itinerary3: Itinerary,
val itinerary4: Itinerary,
val itinerary5: Itinerary,
val itinerary6: Itinerary,
val itinerary7: Itinerary,
val itinerary8: Itinerary,
val itinerary9: Itinerary
),
THE JSON
"itinerary_data" : {
"itinerary_0": {...},
"itinerary_1": {...},
"itinerary_2": {...},
"itinerary_3": {...},
"itinerary_4": {...},
"itinerary_5": {...},
"itinerary_6": {...},
"itinerary_7": {...},
"itinerary_8": {...},
"itinerary_9": {...},
}
</details>
# 答案1
**得分**: 1
你不能直接这样做。因为 JSON 中的行程安排不是数组格式,所以你无法直接得到 Kotlin 列表。一个解决方案是将其解析为 `Map<String, Itinerary>`,然后从地图中获取值的列表。
```kotlin
data class ItinerariesResponse(
@Json(name = "itinerary_data")
val itineraries: Map<String, Itinerary>
)
然后你可以这样获取行程安排的列表:
val response: ItinerariesResponse = yourApiCall()
val itineraries = response.itineraries.values
英文:
You can't do that directly. Because the itineraries in the json are not in array format, so you can't get a Kotlin list out of it. One solution is to parse it as a Map<String, Itinerary>
and then get the list of values from the map.
data class ItinerariesResponse(
@Json(name = "itinerary_data")
val itineraries: Map<String, Itinerary>
)
Then you can get the list of itineraries like this:
val response: ItinerariesResponse = yourApiCall();
val itineraries = response.itineraries.values();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论