Reputation: 1106
I am trying to serialize the json response below, but I am unsure how to do it.
This is the Json my backend returns:
[
{
"title": "Dummy section, should not be seen",
"type": "dummy_test",
"metadata": []
},
{
"title": "Title1",
"type": "categories_products",
"metadata": [
{
"id": "1272"
}
]
},
{
"title": "Title2",
"type": "categories_products",
"metadata": [
{
"id": "996"
}
]
}
]
This is my ExploreItem class:
data class ExploreItem(
@SerializedName("metadata") val metadata: List<Metadata> = listOf(),
@SerializedName("title") val title: String = "",
@SerializedName("type") val type: String = ""
) {
enum class ExploreItemType(val value: String) {
@SerializedName("unknown")
UNKNOWN("unknown"),
@SerializedName("other_companies")
OTHER_COMPANIES("other_companies"),
@SerializedName("categories_products")
CATEGORIES_PRODUCTS("categories_products"),
@SerializedName("popular_categories")
POPULAR_CATEGORIES("popular_categories")
}
}
data class Metadata(
@SerializedName("id") val id: String = ""
)
And now I am trying to serialize it in the repository like this:
Serializer.defaultJsonParser.fromJson(response.body!!.string(),ExploreItem::class.java )
but it doesn't work because it's expecting a list of ExploreItem. How can I rewrite the serializer expression to parse it into a list?
Upvotes: 0
Views: 567
Reputation: 1645
From your error
Type mismatch. Required:List Found:ExploreItem!
Post errors is very important, Gson is telling you that it wants a List and not an object of ExploreItem
.
In other words, you are telling to Gson with the call Serializer.defaultJsonParser.fromJson(response.body!!.string(),ExploreItem::class.java )
"Hey Gson, from the string I want an object ExploreItem
", and Gson is telling you "Hey my friend, you string start with [ ]
for sure it is a list of something and not a single object."
You need to pass in the Serializer.defaultJsonParser.fromJson(response.body!!.string(),List<ExploreItem>::class.java)
P.s: I'm not sure about the Kotlin syntax
Upvotes: 2