将相同类型的多个属性转换为 Kotlin 数据类中这些属性的列表。

huangapple go评论83阅读模式
英文:

Transform multiple properties of the same type to List of these properties in data class Kotlin

问题

在我的应用程序中,我从JSON中检索数据,不幸的是,它的格式不允许我直接获得一个列表。如何将我的数据类转换为只包含一个属性:List< Itinerary >,其中包含这10个(或更多)行程?

  1. data class ItineraryData(
  2. val itineraries: List<Itinerary>
  3. )

JSON数据

  1. "itinerary_data" : {
  2. "itinerary_0": {...},
  3. "itinerary_1": {...},
  4. "itinerary_2": {...},
  5. "itinerary_3": {...},
  6. "itinerary_4": {...},
  7. "itinerary_5": {...},
  8. "itinerary_6": {...},
  9. "itinerary_7": {...},
  10. "itinerary_8": {...},
  11. "itinerary_9": {...}
  12. }
英文:

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?

  1. data class ItineraryData(
  2. val itinerary0: Itinerary,
  3. val itinerary1: Itinerary,
  4. val itinerary2: Itinerary,
  5. val itinerary3: Itinerary,
  6. val itinerary4: Itinerary,
  7. val itinerary5: Itinerary,
  8. val itinerary6: Itinerary,
  9. val itinerary7: Itinerary,
  10. val itinerary8: Itinerary,
  11. val itinerary9: Itinerary
  12. ),

THE JSON

  1. &quot;itinerary_data&quot; : {
  2. &quot;itinerary_0&quot;: {...},
  3. &quot;itinerary_1&quot;: {...},
  4. &quot;itinerary_2&quot;: {...},
  5. &quot;itinerary_3&quot;: {...},
  6. &quot;itinerary_4&quot;: {...},
  7. &quot;itinerary_5&quot;: {...},
  8. &quot;itinerary_6&quot;: {...},
  9. &quot;itinerary_7&quot;: {...},
  10. &quot;itinerary_8&quot;: {...},
  11. &quot;itinerary_9&quot;: {...},
  12. }
  13. </details>
  14. # 答案1
  15. **得分**: 1
  16. 你不能直接这样做。因为 JSON 中的行程安排不是数组格式,所以你无法直接得到 Kotlin 列表。一个解决方案是将其解析为 `Map<String, Itinerary>`,然后从地图中获取值的列表。
  17. ```kotlin
  18. data class ItinerariesResponse(
  19. @Json(name = "itinerary_data")
  20. val itineraries: Map<String, Itinerary>
  21. )

然后你可以这样获取行程安排的列表:

  1. val response: ItinerariesResponse = yourApiCall()
  2. 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&lt;String, Itinerary&gt; and then get the list of values from the map.

  1. data class ItinerariesResponse(
  2. @Json(name = &quot;itinerary_data&quot;)
  3. val itineraries: Map&lt;String, Itinerary&gt;
  4. )

Then you can get the list of itineraries like this:

  1. val response: ItinerariesResponse = yourApiCall();
  2. val itineraries = response.itineraries.values();

huangapple
  • 本文由 发表于 2023年2月19日 19:54:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定