I have the following JSON data
[
{
"type": "carousal",
"items": [
{
"type": "story",
"data": {
"display_name": "grinning 1"
}
},
{
"type": "story",
"data": {
"display_name": "grinning 2"
}
}
]
},
{
"type": "carousal",
"items": [
{
"type": "story",
"data": {
"display_name": "grinning 3"
}
},
{
"type": "story",
"data": {
"display_name": "grinning 4"
}
}
]
}
]
Corresponding data classes are
data class ServerResponse(
@SerializedName("type")
val type: String,
@SerializedName("items")
val subTypes: List<ServerResponse>,
@SerializedName("data")
val data: Data)
data class Data(
@SerializedName("display_name")
val displayName: String)
This is the final data class I want the original object to be converted to
data class ConvertedData(val type: String, val name: String)
This is the kind of response I am looking for using map operator which returns a list convertedData object
[
{
"type": "story",
"display_name": "grinning 1"
},
{
"type": "story",
"display_name": "grinning 2"
},
{
"type": "story",
"display_name": "grinning 3"
},
{
"type": "story",
"display_name": "grinning 4"
}
]
I created an extension to convert the data as
fun ServerResponse.toConvertedData(): ConvertedData? {
val data: ConvertedData? = null
if(type.equals("carousal")){
// compare subtypes type to "story" and put it converted data object
}
return data
}
The commented part I can't figure out since I need to go in the items array and want to use it as follows
val convertedData= serverResponse.map { it.toConvertedData() }
ServerResponseand returning a mapped list withConvertedDataitems. Or You can do it one by one by iterating outside. But map function will help you do it. kotlinlang.org/docs/collection-transformations.html#mapServerResponseinto a singleConvertedDatainstance. You need to get a list ofConvertedDatafrom aServerResponseif you want to get the desired output. Also, if you're only taking the ones with"story"subtype, why do you need to store atypeinConvertedData?