Java 更改json对象值
我有一个类似于上面的json对象,我想更改apiInvokerPublicKey的值,但我在gson中没有找到方法,所以如何更改它Java 更改json对象值,java,json,spring,spring-boot,gson,Java,Json,Spring,Spring Boot,Gson,我有一个类似于上面的json对象,我想更改apiInvokerPublicKey的值,但我在gson中没有找到方法,所以如何更改它 { "onboardingInformation": { "apiInvokerPublicKey": "string", "apiInvokerCertificate": "string", "onboardingSecret&
{
"onboardingInformation": {
"apiInvokerPublicKey": "string",
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
编辑:我使用了gson的addProperty方法,但它改变了整个“onboardingInformation”,我只想改变“apiInvokerPublicKey”您可以将整个
JSON
负载读取为JsonObject
并覆盖现有属性。之后,您可以将其序列化回JSON
{
"onboardingInformation": {
"apiInvokerPublicKey": "abcacabcascvhasj",// i want to change just this part
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
以上代码打印:
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);
}
}
我使用jacksonapi方法提供代码片段
{
"onboardingInformation": {
"apiInvokerPublicKey": "NEW VALUE",
"apiInvokerCertificate": "string",
"onboardingSecret": "string"
},
"notificationDestination": "string",
"requestTestNotification": true
}
你能解释一下你打算如何改变价值吗?描述输入和预期输出将有助于为您提供更好的解决方案。
//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);