How to modify an existing json file with Java (add an extra param)

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:




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!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s