JSONObject remove empty value pairs

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

Here is my Json File:

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


        
6条回答
  •  执念已碎
    2021-01-05 09:34

    In Scala with org.json library, can be easily converted to Java (although a bit more verbose). Recursively removes nulls and empty objects/arrays:

    import org.json.{ JSONArray, JSONObject }
    
    object JsonCleaner {
    
      def clean(json: JSONObject): Boolean = {
        val i = json.keys()
        while (i.hasNext) clean(i, json.get(i.next()))
        json.length == 0
      }
    
      def clean(json: JSONArray): Boolean = {
        val i = json.iterator()
        while (i.hasNext) clean(i, i.next())
        json.length == 0
      }
    
      private def clean(i: java.util.Iterator[_], v: Any) {
        v match {
          case o: JSONObject =>
            if (clean(o)) i.remove()
          case a: JSONArray =>
            if (clean(a)) i.remove()
          case JSONObject.NULL | "" =>
            i.remove()
          case _ =>
        }
      }
    
    }
    

提交回复
热议问题