将多个jsonArray合并(scala)

因为业务需求,要将多个jsonArray合并,使用scala分分钟实现,代码异常简洁。

代码

object test extends App{

//构造jsonArray
val obj1 = new JSONObject()
  obj1.put("name","breeze")
  obj1.put("age",22)
val obj2 = new JSONObject()
  obj2.put("name","lsw")
  obj2.put("age",20)
  obj2.put("addr","hangzhou")
//arr1有2个obj
val jsonArray1 = new JSONArray()
  jsonArray1.put(obj1)
  jsonArray1.put(obj2)
//arr2有一个obj
val jsonArray2 = new JSONArray()
  jsonArray2.put(obj2)  
//arr3为空 
val jsonArray3 = new JSONArray()

/** * 接收参数为任意个数的String(jsonArray) * 将其合并为一个 */
def combineJsonArray(arrs: String*): String ={
    val jsonArray = new JSONArray()
    for (arr <- arrs){
    //排除空值
        if(StringUtils.isNotBlank(arr)){
          val jSONArray = new JSONArray(arr)
          for(i <- 0 until jSONArray.length()){
            jsonArray.put(jSONArray.getJSONObject(i))
          }
        }
    }    
    jsonArray.toString()
  }
}

//不同参数输出
println("3args:"+ combineJsonArray(jsonArray1.toString,jsonArray2.toString,jsonArray3.toString))

println("2args:"+ combineJsonArray(jsonArray1.toString,jsonArray2.toString))

println("1args:"+ combineJsonArray(jsonArray1.toString))

输出结果

3args:[{"name":"breeze","age":22},{"name":"lsw","age":20,"addr":"hangzhou"},{"name":"lsw","age":20,"addr":"hangzhou"}]

2args:[{"name":"breeze","age":22},{"name":"lsw","age":20,"addr":"hangzhou"},{"name":"lsw","age":20,"addr":"hangzhou"}]

1args:[{"name":"breeze","age":22},{"name":"lsw","age":20,"addr":"hangzhou"}]

你可能感兴趣的:(scala)