How do I add another empty JsonObject node if not already present in json file in java?

Viewed 277

My current JSON file:

{
    "dev": {
        "name": "James",
        "address": "12 VK Street",
        "city": "Austin"
    },
    "test": {
        "name": "Roy",
        "address": "15 VK Street",
        "city": "New York"
    }
}

I have another environment called beta.
Need to check if beta node exists in current JSON file.
If beta exists in current JSON file then its ok and no changes in JSON file.
If beta node does not exists then I need to add node for beta and update JSON file to following.

{
    "dev": {
        "name": "James",
        "address": "12 VK Street",
        "city": "Austin"
    },
    "test": {
        "name": "Roy",
        "address": "15 VK Street",
        "city": "New York"
    }
    "beta": {
    }
}

I tried following code but it didn't work.
Checking if JSON has desired object already. If not then create a new one

JSONObject main = new JSONObject(jsonString);
    if (!main.has("beta")) {
        main.put("beta", new JSONObject());
        // main.put("beta", ""); didn't work
        // main.put("beta", "{}"); didn't work
}

How can I achieve this in Java ? I tried using Jackson, Simple JSON but it didn't work out. Thanks!

===========================

Got it working

private void addReplaceValueInJson(String key, String value) throws Exception {
        File jsonFile = new File("testdata.json");
        String jsonString = FileUtils.readFileToString(jsonFile, Charset.defaultCharset());
        String env = System.getProperty(Constant.ENV);

        JsonElement mainElement = new JsonParser().parse(jsonString);
        JsonObject mainObject = mainElement.getAsJsonObject();

        // If env node is not present in json then create one
        if (!mainObject.has(env)) {
            JsonElement envElement = new JsonParser().parse(new JSONObject("{}").toString());
            mainObject.add(env, envElement);
        }

        try {
            mainObject.getAsJsonObject(env).addProperty(key, value);
            String resultingJson = new Gson().toJson(mainElement);
            FileUtils.writeStringToFile(jsonFile, resultingJson, Charset.defaultCharset());
        } catch (Exception e) {
            System.out.println("JSONObject: " + env + " missing in testdata.json. Please add " + env + " node.");
        }
    }

This will add child jsonobject if it is not present. And update key's value or add new one in place of entire file flush n close

0 Answers
Related