Skip to content
Advertisement

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”

Advertisement

Answer

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
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement