gson 更改json对象值

whlutmcx  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(255)
{
  "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”

iqxoj9l9

iqxoj9l91#

您可以将整个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
}
wyyhbhjk

wyyhbhjk2#

我提供了使用Jacksonapi方法的代码片段

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

相关问题