Reputation: 339
{
"onboardingInformation": {
"apiInvokerPublicKey": "string",
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
I have a json object like above and i want to change apiInvokerPublicKey's value i did not find a method in gson so how can i change it?
{
"onboardingInformation": {
"apiInvokerPublicKey": "abcacabcascvhasj",// i want to change just this part
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
EDIT: I used addProperty method from gson but it changes whole "onboardingInformation" i just want to change "apiInvokerPublicKey"
Upvotes: 2
Views: 3485
Reputation:
I am providing code snippet using Jackson api approach
//Read JSON and populate java objects
ObjectMapper mapper = new ObjectMapper();
Test test = mapper.readValue(ResourceUtils.getFile("classpath:test.json") , "Test.class");
//do the required change
test.setApiInvokerPublicKey("updated value");
//Write JSON from java objects
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(new File("result.json"), person);
Upvotes: 0
Reputation: 38665
You can read whole JSON
payload as JsonObject
and overwrite existing property. After that, you can serialise it back to JSON
.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class GsonApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject root = gson.fromJson(Files.newBufferedReader(jsonFile.toPath()), JsonObject.class);
JsonObject information = root.getAsJsonObject("onboardingInformation");
information.addProperty("apiInvokerPublicKey", "NEW VALUE");
String json = gson.toJson(root);
System.out.println(json);
}
}
Above code prints:
{
"onboardingInformation": {
"apiInvokerPublicKey": "NEW VALUE",
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
Upvotes: 4