如何在Java中修改json字符串?

时间:2019-04-04 19:36:07

标签: java json

我有一个类似json的字符串

{"egcnbrandcid":5555444433332220,"egcstatus":"CARD NOT ON EGC DATABASE","egcbalance":0.00}

如何在Java中安全地修改字符串?

为了安全起见,我的意思是说在完成修改后,我仍然需要一个有效的json字符串。在这种情况下,我会将数字转换为字符串,其输出如下所示:

{"egcnbrandcid":"redacted","egcstatus":"CARD NOT ON EGC DATABASE","egcbalance":0.00}  

请注意,Json字符串并不总是包含这些相同的字段,这一点很重要。

2 个答案:

答案 0 :(得分:0)

您可以使用JSONParser(),不需要创建Java对象来保存,它的工作方式类似于Map

 public static void main(String[] args) throws Exception  
    { 
        // parsing file "JSONExample.json" 
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); 

        // typecasting obj to JSONObject 
        JSONObject jo = (JSONObject) obj; 

        // getting firstName and lastName 
        String firstName = (String) jo.get("firstName"); 
        String lastName = (String) jo.get("lastName"); 

        System.out.println(firstName); 
        System.out.println(lastName); 

        // getting age 
        long age = (long) jo.get("age"); 
        System.out.println(age); 

        // getting address 
        Map address = ((Map)jo.get("address")); 

        // iterating address Map 
        Iterator<Map.Entry> itr1 = address.entrySet().iterator(); 
        while (itr1.hasNext()) { 
            Map.Entry pair = itr1.next(); 
            System.out.println(pair.getKey() + " : " + pair.getValue()); 
        } 

        // getting phoneNumbers 
        JSONArray ja = (JSONArray) jo.get("phoneNumbers"); 

        // iterating phoneNumbers 
        Iterator itr2 = ja.iterator(); 

        while (itr2.hasNext())  
        { 
            itr1 = ((Map) itr2.next()).entrySet().iterator(); 
            while (itr1.hasNext()) { 
                Map.Entry pair = itr1.next(); 
                System.out.println(pair.getKey() + " : " + pair.getValue()); 
            } 
        } 

答案 1 :(得分:0)

受@Yiao Sun的回答启发,我编写了以下递归函数

    private void modJO(JSONObject job){
    Iterator keys = job.keys();
    while(keys.hasNext()) {
        String currentKey = (String)keys.next();
        JSONObject job2 = job.optJSONObject(currentKey);
        JSONArray jar = job.optJSONArray(currentKey);
        // If JSON Object
        if(job2 != null){
            modJO(job2);
        }
        // If JSON Array
        else if(jar != null){
            modJA(jar);
        }
        // If JSON Property
        else {
            if(currentKey.equals("cid")){
                try{
                    job.put(currentKey,"redacted");
                }
                catch(Exception ex){}
            }
        }
    }
}

private void modJA(JSONArray jar){
    for(int i = 0; i < jar.length(); i++){
        JSONObject job = jar.optJSONObject(i);
        JSONArray jar2 = jar.optJSONArray(i);

        if (job != null){
            modJO(job);
        }
        else if (jar2 != null){
            modJA(jar2);
        }
    }
}

我在此对象上进行了测试,该对象应涵盖所有可能的情况

{
                notSecret: 'jetFuelCantMeltSteelBeams',
                cid: 'superSecret',
                obj: { cid: 'moreSecret' },
                objObj: { child: { cid: 'itsASecretToEverybody' } },
                array: [1, 2, 3],
                objArr: [{ cid: 'topSecret' }, { cid: 'iCantBelieveItsSecret' }],
                arrArr: [[1, 2], [1, 2]],
                mixed: [
                    { name: 'Waldo' },
                    { cid: 'unbelievablySecret' },
                    7,
                    [{ name: 'HeisenBurg' }, 9]
                ],
                emptyObj: {},
                emptyArr: []
            }  

最终结果是

{
                objObj: { child: { cid: 'redacted' } },
                arrArr: [[1, 2], [1, 2]],
                emptyArr: [],
                array: [1, 2, 3],
                obj: { cid: 'redacted' },
                objArr: [{ cid: 'redacted' }, { cid: 'redacted' }],
                mixed: [{ name: 'Waldo' }, { cid: 'redacted' }, 7, [{ name: 'HeisenBurg' }, 9]],
                emptyObj: {},
                notSecret: 'jetFuelCantMeltSteelBeams',
                cid: 'redacted'
            }

这是我的称呼方式

    private String modifyJsonObject(String jsonString){
    String json = "{\"notSecret\": \"jetFuelCantMeltSteelBeams\",\"cid\": \"superSecret\",\"obj\": { \"cid\": \"moreSecret\" },\"objObj\": { \"child\": { \"cid\": \"itsASecretToEverybody\" } },\"array\": [1, 2, 3],\"objArr\": [{ \"cid\": \"topSecret\" }, { \"cid\": \"iCantBelieveItsSecret\" }], \"arrArr\": [[1, 2], [1, 2]],\"mixed\": [{ \"name\": \"Waldo\" },{ \"cid\": \"unbelievablySecret\" },7,[{ \"name\": \"HeisenBurg\" }, 9]],\"emptyObj\": {},\"emptyArr\": []}";
    try {
        JSONObject jObject  = new JSONObject(json);
        modJO(jObject);
        return jObject.toString();
    }
    catch(Exception ex){
        int stop  = 4;
    }
    return "";
}