So I've recently been tasked with creating a utility which will allow easy addition of JSON to a .json file via the gson library. I've coded this in Kotlin:
fun addObject(filePath: String, name: String, values: Array<Array<String>>) {
try {
var writer: JsonWriter = JsonWriter(FileWriter(File(filePath)))
writer.beginObject()
writer.name(name)
writer.beginObject()
for(item in values){
writer.name(item[0]).value(item[1])
}
writer.endObject()
writer.endObject()
writer.close()
println("[JSONUtil] Wrote object successfully!")
} catch (e: IOException) {
e.printStackTrace()
}
}
I used a 2 Dimensional array to allow the user to add different objects with any number of values in said object. For instance, you would run it like so:
addObject("C:\\Users\\Test\\Desktop\\JsonUtility\\output.json", "GENERAL",
arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")))
This creates the following JSON:
{"GENERAL":{"POS_X":"2","POS_Y":"4"}}
This is how it was intended and works, my issue is that upon running the function again it completely overwrites the previous JSON in the file, and this is obviously bad.
My questions are:
How can I add new JSON objects inside the entire file, or at specific points, like "addObject("GENERAL", ...)" for this example?
How can I make this better?
I'm fairly new to Kotlin and have been coding in Java mostly, so Java solutions are fine as I'm sure I'll be able to convert it.
Thanks in advance!
EDIT: New Code, no idea how to implement it:
fun UpdateJson(path: String, name: String, value: String){
var gson = Gson()
var reader: FileReader = FileReader(File(path))
val type = object : TypeToken<Map<String, String>>() {}.type
println("Type: " + type.toString())
println("Existing Json: ${gson.fromJson<Map<String,String>>
(JsonReader(reader), type)}")
var existingJson: Map<String, String> =
gson.fromJson<Map<String,String>>(JsonReader(reader), type)
existingJson.put(name, value)
FileWriter(File(path)).use({ writer ->
writer.write(gson.toJson(existingJson)) })
}