简体   繁体   English

如何修改java中的json字符串?

[英]How do I modify a json string in java?

I have a json string like 我有一个json字符串

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

How can I modify the string safely in java? 如何在java中安全地修改字符串?

By safely I mean that I still need a valid json string after I'm done modifying it. 安全地我的意思是在我完成修改之后我仍然需要一个有效的json字符串。 In this case I would be converting the number to a string with the output looking like: 在这种情况下,我将数字转换为字符串,输出如下:

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

It's important to note that the Json string won't always contain these same fields. 值得注意的是,Json字符串并不总是包含这些相同的字段。

You can use JSONParser(), you don't need create java objects to save, It works like Map 你可以使用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()); 
            } 
        } 

Inspired by @Yiao Sun's answer I wrote the following recursive functions 受@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);
        }
    }
}

And I tested it on this object which should cover all possible scenarios 我在这个对象上测试了它,它应该涵盖所有可能的场景

{
                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: []
            }  

Final result is 最终结果是

{
                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'
            }

Here's how I called it 这就是我打电话的方式

    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 "";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM