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

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

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

&quot;itinerary_data&quot; : {
      &quot;itinerary_0&quot;: {...},
      &quot;itinerary_1&quot;: {...},
      &quot;itinerary_2&quot;: {...},
      &quot;itinerary_3&quot;: {...},
      &quot;itinerary_4&quot;: {...},
      &quot;itinerary_5&quot;: {...},
      &quot;itinerary_6&quot;: {...},
      &quot;itinerary_7&quot;: {...},
      &quot;itinerary_8&quot;: {...},
      &quot;itinerary_9&quot;: {...},
}

</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&lt;String, Itinerary&gt; and then get the list of values from the map.

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

Then you can get the list of itineraries like this:

val response: ItinerariesResponse = yourApiCall();
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:

确定