更改json对象的值

问题描述

{
  "onboarding@R_77_4045@ion": {
    "apiInvokerPublicKey": "string","apiInvokerCertificate": "string","onboardingSecret": "string"
  },"notificationDestination": "string","requestTestNotification": true
}

我有一个如上所述的json对象,我想更改apiInvokerPublicKey的值,但我在gson中找不到方法,该如何更改?

{
  "onboarding@R_77_4045@ion": {
    "apiInvokerPublicKey": "abcacabcascvhasj",// i want to change just this part
    "apiInvokerCertificate": "string","requestTestNotification": true
}

编辑:我使用了gson的addProperty方法,但它更改了整个“ onboarding@R_77_4045@ion”,我只想更改“ apiInvokerPublicKey”

解决方法

您可以将整个column_index = 1 columns = {} for column_node in response.xpath('//*[@id="sched_ks_3260_1"]/thead/tr/th'): column_name = column_node.xpath('./text()').extract_first() columns[column_name] = column_index column_index += 1 matches = [] for row in response.xpath('//*[@id="sched_ks_3232_1"]//tbody/tr'): match = {} for column_name in columns.keys(): match[column_name] = row.xpath('./td[{index}]//text()'.format(index=columns[column_name])).extract_first() matches.append(match) 有效负载读取为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);
    }
}
,

我正在使用 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);