I have a large JSON file that I need to work with in a Kotlin (android) project. Due to its size, I’m considering converting it to a different file format for better performance or easier handling.
What would be the safest and most compatible file format to convert this JSON file into, while still being easily readable and usable in Kotlin?
Any recommendations or best practices would be appreciated!
You could try YAML, but I think the format matters less than the way you read it. There are streaming libraries available for many formats, including JSON.
Also, there is a “compressed JSON” format called CBOR, if the file doesn’t have to be human readable: https://cbor.io/
I have recently migrated a Java app to kotlin. This app uses json. In one area it used Gson to read a file with fields from a single class:
@java
newParams = new Gson().fromJson(reader,NewParameters.class);
In other areas I read the various elements:
@kotlin
jsonReader = JsonReader(FileReader(exchangeFile))
nodes= JsonParser.parseReader(jsonReader).asJsonObject
buildNode = nodes.get("build")
linesNode = nodes.get("lines")
if (linesNode.isJsonArray){
try {
val linesArray = linesNode.asJsonArray
for (i in 0..linesArray.size() - 1) {
var lineObject = linesArray.get(i).asJsonObject
val exchangeNode = lineObject.get("exchange")
val nameNode = lineObject.get("name")
val currencyNode = lineObject.get("currency")
val exchangeConfig = ExchangeConfig()
exchangeConfig.name = nameNode.asString
exchangeConfig.currencyID= currencyNode.asString
exchanges.put(exchangeNode.asString, exchangeConfig)
}
}
catch (e : Exception){
throw(PriceLoaderConfigException("Error loading Exchanges - $e.message"))
}
}
jsonReader.close()
This code loads a file of 100 entries.
You don’t say why the file is large. Does it have loads of different structures or is it several entries of the same structure as above? If it is the latter the code will be quite easy and relatively small. If the former then obviously you have to cater for the different structures and then you should think about a smaller encoding.