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

问题描述 投票:0回答:1

我需要在运行脚本时每次更改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...!!");
        }
    }
}

}
java json
1个回答
0
投票

我假设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());
© www.soinside.com 2019 - 2024. All rights reserved.