JSONObject remove empty value pairs

前端 未结 6 1076
暖寄归人
暖寄归人 2021-01-05 09:06

Here is my Json File:

{  
   \"models\":{},
   \"path\":[  
      {  
         \"path\":\"/web-profiles\",
         \"operations\":[  
            {  
               


        
6条回答
  •  逝去的感伤
    2021-01-05 09:40

    Regex solution

    You could use REGEX to remove any line from your data that conatins a "",[],or {} before you parse it with the JSONParser.

    The regex for something like this would look like. Keep in mind that you may have to adjust the new line character depending on your OS

    [^\n]*(\"(\n)*\"|\[(\n)*\]|\{(\n)*\})[^\n]*
    

    To account for an instance where the JSON data is as follows

    {  
       "models":{},
       "path":[  
          {  
             "path":"/web-profiles",
             "operations":[  
                {  
                   "nickname":"",
                   "type":"",
                   "responseMessages":[]
                }
             ]
          }
       ],
       "produces":[]
    }
    

    The first time you run that replaceAll it will result with

    {  
       "path":[  
          {  
             "path":"/web-profiles",
             "operations":[  
                {  
                }
             ]
          }
       ],
    }
    

    Now we an empty JSONObject inside of the "operations" JSONArray. So this replaceAll function needs to be called again untill the JSON String doesn't have any changes from it's previous state.

    Keep in mind that if you use functions like readLine() during data input it can remove the newline character which will make this method not work. So solve this replace your read line with this.

    json += in.readLine() + '\n';
    

    Here is a quick program I wrote that does the actual removal of empty json objects from the original String.

    public static void main(String[] args){
        // String from above example with newline characters intact
        String json = "{\n\"models\":{},\n\"path\":[\n{\n\"path\":\"/web-profiles\",\n\"operations\":[\n{\n\"nickname\":\"\",\n\"type\":\"\",\n\"responseMessages\":[]\n}\n]\n}\n],\n\"produces\":[]\n}";
    
        // Value from the last iteration of the while loop
        String last = "";
        // If there was no change from the last replaceAll call stop
        while( !last.equals(json) ){
            last = json;
            // Same regex as above just escaped to work in a Java String
            json = json.replaceAll("[^\\n]*(\\{(\\n)*\\}|\\\"(\\n)*\\\"|\\[(\\n)*\\])[^\\n]*\\n","");
        }
    
        System.out.println(json);
    }
    

提交回复
热议问题