我需要在运行脚本时每次更改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...!!");
}
}
}
}
答案 0 :(得分:0)
我假设 application_id 的值属于 APPLICATION , AATCL_MAIN 和 A_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());