gpt4 book ai didi

java - 如何在java中替换/更新嵌套的json文件值?

转载 作者:行者123 更新时间:2023-12-01 23:46:21 44 4
gpt4 key购买 nike

我每次运行脚本时都需要更改application_id!预先感谢用java解释!

我的 json 文件如下:-

{
"APPLICATION": [{
"application_id": "4884850",
"appl_purpose_code": "LN",
"original_purpose": "LN",
"appl_status_code": "S"
}],
"AATCL_MAIN": [{
"application_id": "4884850",
"other_wireless_ind": "N",
"seek_rural_bc": "N"
}],
"A_LICENSE": [{
"application_id": "4884850",
"a_alien_officer": "N",
"a_alien_control": "N"
}]
}

我的java代码如下:-

import java.io.File;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.IOException;

import org.json.JSONObject;

import org.testng.annotations.Test;

import com.fasterxml.jackson.core.JsonParseException;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class testing {

@Test
public void replaceText() throws JsonParseException, JsonMappingException, IOException {

ObjectMapper mapper = new ObjectMapper();
String key = "key"; //whatever

//("{key1:\"val1\", key2:\"val2\"}")

JSONObject jo = new JSONObject("{APPLICATION[0].application_id:\"4884852\"}");
//Read from file
JSONObject root = mapper.readValue(new File("jsonFileInputPost\\jsonGrouponePostFullContent.json"), JSONObject.class);

String val_newer = jo.getString(key);
String val_older = root.getString(key);

//Compare values
if(!val_newer.equals(val_older))
{
//Update value in object
root.put(key,val_newer);

//Write into the file
try (FileWriter file = new FileWriter("jsonFileInputPost\\jsonGrouponePostFullContent.json"))
{
file.write(root.toString());
System.out.println("Successfully updated json object to file...!!");
}
}
}

}

最佳答案

我假设application_id的值属于APPLICATIONAATCL_MAINA_LICENSE是相同的,那么你可以判断给定的JSON字符串是否会被更新,如下:

String jsonStr = "{\"APPLICATION\":[{\"application_id\":\"4884850\",\"appl_purpose_code\":\"LN\",\"original_purpose\":\"LN\",\"appl_status_code\":\"S\"}],\"AATCL_MAIN\":[{\"application_id\":\"4884850\",\"other_wireless_ind\":\"N\",\"seek_rural_bc\":\"N\"}],\"A_LICENSE\":[{\"application_id\":\"4884850\",\"a_alien_officer\":\"N\",\"a_alien_control\":\"N\"}]}";

String applicationIdNew = "4884852";
ObjectMapper mapper = new ObjectMapper();
String applicationId = mapper.readTree(jsonStr).get("APPLICATION").get(0).get("application_id").asText();

ObjectNode root = (ObjectNode) mapper.readTree(jsonStr);
if (!applicationIdNew.equals(applicationId)) {
((ObjectNode) root.get("APPLICATION").get(0)).put("application_id", applicationIdNew);
((ObjectNode) root.get("AATCL_MAIN").get(0)).put("application_id", applicationIdNew);
((ObjectNode) root.get("A_LICENSE").get(0)).put("application_id", applicationIdNew);
}
System.out.println(root.toString());

关于java - 如何在java中替换/更新嵌套的json文件值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239462/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com