Okay, so you have a json file somewhere, that was already created by someone else, by another project or just due to quantum fluctuation… doesn’t matter, what you want is to read that file, read the json, add another property to that json and then write the entire json back to the file.
Of course it’s not that complicated and can be done in so many ways. I saw a lot of projects that were doing this by simply manipulating the string. This is certainly not recommended since it’s pretty easy to screw up the integrity of that json object.
Instead let’s see one of the easiest and safest way to do it:
You will need Google Gson and Apache Commons-IO or Google Guava:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
Now the java code:
File jsonFile = new File("myfile.json"); // Commons-IO String jsonString = FileUtils.readFileToString(jsonFile); // Guava String jsonString = Files.toString(jsonFile, Charsets.UTF_8); JsonElement jelement = new JsonParser().parse(jsonString); JsonObject jobject = jelement.getAsJsonObject(); jobject.addProperty("isThisCodeAmazing", Boolean.TRUE); Gson gson = new Gson(); String resultingJson = gson.toJson(jelement); // Commons-IO FileUtils.writeStringToFile(jsonFile, resultingJson); // Guava Files.write(resultingJson, jsonFile, Charsets.UTF_8);
Pretty nice… only 7 lines. Of course, it can be better. Even in groovy is easier 🙂
Now let’s have fun spreading joy!