'change the json object value

{
  "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"



Solution 1:[1]

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
}

Solution 2:[2]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michał Ziober
Solution 2