I have an app that stores client data in a local Room DB. I have added an option to export clients list as Json file. Everything works fine except that data in exported json file is ordered alphabetically by value names.
Room Data Class
@Entity(tableName = "clients")
data class ClientData(
@PrimaryKey(autoGenerate = true)
val clientId: Long?,
var name: String,
var eMail: String? = null,
var phone: String? = null,
var businessNumber: String? = null,
@Embedded
var address: Address?
)
Address Class
data class Address(
var fullAddress: String? = null,
var city: String? = null,
var state: String? = null,
var zip: String? = null,
var country: String? = null
)
JSON Export
private fun exportClientsJson(file: File, clients: List<ClientData>) {
val prettyJson = GsonBuilder().setPrettyPrinting().create()
val jsonClients = prettyJson.toJson(clients)
file.writeText(jsonClients)
}
Exported File
[
{
"address": {
"city": "",
"country": "",
"fullAddress": "",
"state": "",
"zip": ""
},
"clientId": 1,
"eMail": "nick@gmail.com",
"name": "Nick",
"phone": "1234567890"
}
]
As you can see order of values is not the same as in data class. It places everything alphabetically by keys for main (ClientData) and nested class (Address). I also tried simple json string ( Gson().toJson(clients)
) - it is the same thing, just in one line. I mean it is probably useful in many cases, but I do not really want this. I never worked with json in android\kotlin. Is it normal behavior? Is it possible to disable this auto sort?