[Solved] Adding JSON objects to existing JSON File


The easiest way is to, as @KrisRoofe suggested, read the json, then add an element. I would do this by converting the existing json in the file to a Map. Since you don’t actually care about the existing json, all you want to do is add a new entry to that Map. Once you do that, simply write the new Map to the File. You can do this like so:

public class UpdateJson {
    public static void main(String[] args) throws IOException {
        addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")));
    }

    private static void addObject(String fileName, String newObjName, String newObjValue) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> existingJson = gson.fromJson(new JsonReader(new FileReader(new File(fileName))), type);
        existingJson.put(newObjName, newObjValue);
        try (FileWriter writer = new FileWriter(new File(fileName))) {
            writer.write(gson.toJson(existingJson));
        }
    }

    private static String arrayOf(String s1, String s2) {
        return "[" + s1 + ", " + s2 + "]";
    }
}

EDIT:
The above solution is a Java solution. There seems to be an issue with the Type in Kotlin.

  1. This Stack Overflow question has a workaround by using object:
  2. Also, note that to use reflection with Kotlin, you need a separate jar, according to Kotlin documentation

EDIT 2: Provided Kotlin Answer:

fun main(args: Array<String>) {
    addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X", "2"), arrayOf("POS_Y", "4")))
}


fun addObject(path: String, name: String, value: String) {
    val gson = Gson()
    val reader: FileReader = FileReader(File(path))
    val type = object : TypeToken<Map<String, String>>() {}.type
    System.out.println("Type: " + type.toString())
    val existingJson = gson.fromJson<Map<String, String>>(JsonReader(reader), type)
    System.out.println("Existing Json: ${existingJson}")
    val newJsonMap = existingJson.plus(Pair(name, value))
    FileWriter(File(path)).use(
        { writer -> writer.write(gson.toJson(newJsonMap)) }
    )
}

fun arrayOf(s1: String, s2: String): String {
    return "[$s1, $s2]"
}

23

solved Adding JSON objects to existing JSON File