I have a data class which has a property whose type is another data class, like this:
@Serializable
data class Vehicle (
val color: String,
val miles: Int,
val year: Int,
val garage: Garage
)
@Serializable
data class Garage (
val latitude: Float,
val longitude: Float,
val name: String
)
Upon serializing, it produces output like this:
{
"color" : "black" ,
"miles" : 35000 ,
"year" : 2017 ,
"garage" : { "latitude" : 43.478342 , "longitude" : -91.337000 , "name" : "Paul's Garage" }
}
However I would like garage
to be a literal string of its JSON representation, not an actual JSON object. In other words, the desired output is:
{
"color" : "black" ,
"miles" : 35000 ,
"year" : 2017 ,
"garage" : "{ \"latitude\" : 43.478342 , \"longitude\" : -91.337000 , \"name\" : \"Paul's Garage\" }"
}
How can I accomplish this in Kotlin? Can it be done with just kotlinx.serialization
or is Jackson/Gson absolutely necessary?
Note that this output is for a specific usage. I cannot overwrite the base serializer because I still need to serialize/deserialize from normal JSON (the first example). In other words, the best scenario would be to convert the first JSON sample to the second, not necessarily to have the data class produce the 2nd sample directly.
Thanks!
Create a custom
SerializationStrategy
forVehicle
as follows:Then pass it to
Json.encodeToString()
:Result:
More info here