Reputation: 25
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?
Upvotes: 0
Views: 2744
Reputation: 2080
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));
System.out.println(f3obj);
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;
Upvotes: 1
Reputation: 1379
You can create new Json from the given response values.
def jsonData = new JsonSlurper().parseText(response.contentAsString)
And you can use the JSONObject as follows:
JSONObject newStudent = jsonData.getJSONObject("student");
newStudent.put("name", "John");
If you get an Array as a response use the following code:
JSONObject newStudent = jsonData.getJSONObject(0).getJSONObject("student");
nweStudent.put("name", "John");
For building JSON using a builder you can use the Json builder:
def builder = new JsonBuilder()
builder([
[type: 'string', values: ['no', 'name', 'here']]
])
Upvotes: 0