更改 json 对象值

change the json object value

{
  "onboardingInformation": {
    "apiInvokerPublicKey": "string",
    "apiInvokerCertificate": "string",
    "onboardingSecret": "string"
  },
  "notificationDestination": "string",
  "requestTestNotification": true
}

我有一个像上面那样的 json 对象,我想更改 apiInvokerPublicKey 的值我没有在 gson 中找到方法,所以我该如何更改它?

{
  "onboardingInformation": {
    "apiInvokerPublicKey": "abcacabcascvhasj",// i want to change just this part
    "apiInvokerCertificate": "string",
    "onboardingSecret": "string"
  },
  "notificationDestination": "string",
  "requestTestNotification": true
}

编辑:我使用了 gson 的 addProperty 方法,但它改变了整个“onboardingInformation”,我只想改变“apiInvokerPublicKey”

您可以将整个 JSON 有效负载读取为 JsonObject 并覆盖现有的 属性。之后,您可以将其序列化回 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);
    }
}

以上代码打印:

{
  "onboardingInformation": {
    "apiInvokerPublicKey": "NEW VALUE",
    "apiInvokerCertificate": "string",
    "onboardingSecret": "string"
  },
  "notificationDestination": "string",
  "requestTestNotification": true
}

我使用 Jackson api 方法

提供代码片段
//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);