Pardeep Sharma
01/15/2025, 3:38 PMPardeep Sharma
01/15/2025, 3:38 PMFrank Bouwens
01/15/2025, 4:05 PMpackage com.example.example
import com.google.gson.annotations.SerializedName
data class ExampleJson2KtKotlin (
@SerializedName("type" ) var type : String? = null,
@SerializedName("id" ) var id : Int? = null,
@SerializedName("lastUpdated" ) var lastUpdated : Int? = null,
@SerializedName("title" ) var title : String? = null,
@SerializedName("description" ) var description : String? = null,
@SerializedName("imageURL" ) var imageURL : String? = null,
@SerializedName("likes" ) var likes : Int? = null,
@SerializedName("shares" ) var shares : Int? = null
)
Source :
https://json2kt.com/Michael Krussel
01/15/2025, 4:11 PMChrimaeon
01/15/2025, 5:18 PMtype
and move it up a hierarchy so to have a list with the individual types. then your paring would not require empty fields.
{
"article": [
<list of articles>
],
"video": [
<list of videos>
]
}
Arne Jans
01/15/2025, 5:28 PMval moshi = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(RssFeedEntry::class.java, "type")
.withSubtype(ArticleFeedEntry::class.java, "article")
.withSubtype(VideoFeedEntry::class.java, "video")
.withSubtype(Advertisement::class.java, "advertisement"),
)
.build()
This would save you the hassle of having to define optional fields, since you would have a clean separation per subtype.
You can put common JSON-fields like type
and ID
into the abstract class RssFeedEntry
.
For me, deserialization of a Long
-type common field did not work, though, I had to declare it as Int
to work correctly (which might not be an option for lastUpdated
), but you can always duplicate Long
-fields for each needed usage in a subtype.
Here are the details for this PolymorphicJsonAdapterFactor
of Moshi:
https://github.com/square/moshi/blob/ed3e66b1a94e1efd36853e5779011e5ae1b60843/mosh[…]va/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.ktArne Jans
01/15/2025, 5:40 PMPardeep Sharma
01/16/2025, 4:40 AM