【问题标题】:change the json object value更改 json 对象值
【发布时间】:2023-03-25 11:26:01
【问题描述】:
{
  "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”

【问题讨论】:

  • 您能否解释一下您打算如何更改该值?描述输入和预期输出将有助于为您提供更好的解决方案。

标签: java json spring spring-boot gson


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我正在使用 Jackson api 方法提供代码 sn-p

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 2017-07-20
      • 1970-01-01
      • 2021-04-16
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多