TAP TAP - 3 months ago 15
Java Question

Change a value in a json file using jsonparser

I am very new to Java but have figured out how to extract values from a json file - but I can not understand how to change the value.

JsonElement staff = gson.fromJson(new FileReader("file1.json"), JsonElement.class);
String json = gson.toJson(staff);
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(json);
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f3obj = ((JsonObject) ((JsonObject) ((JsonArray) jsonObject.get("Options")).get(1)).get("Option").get("Dialog");

How can I update the value of "Dialog" in this object?


You can update using below mentioned code.

        JsonObject f3obj = ((JsonArray) jsonObject.get("Options")).get(1).getAsJsonObject().get("Option").getAsJsonObject();
        f3obj.addProperty("Dialog", new Integer(10));

I am using Guava library so below mentioned packages are being used.

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;