2016-03-21 33 views
1

下面的代碼顯示了一個示例JSON,我試圖評估它。如何在Groovy中使用JSON中的空值或缺少鍵/值對

拳頭2聲明的聲明工作,但其餘不。 任何幫助將是偉大的。

代碼:

import groovy.json.* 

def jsonText = ''' 
{ 
    "message": { 

      "employees": [{ 
       "firstName": "John", 
       "lastName": "Doe", 
       "age": 1 
      }, { 
       "firstName": "Anna", 
       "lastName": "Smith", 
       "age": 5 
      }, { 
       "firstName": "Peter", 
       "lastName": "Jones" 

      }], 

     "body": "Some message" 
    } 
}   
''' 

def json = new JsonSlurper().parseText(jsonText) 

def message= json.message 
assert message.employees[0].age == 1 
assert message.employees.size() == 3 

// How to make the following tests work. Are there any options? 
assert message.employees.age.size() == 2  // How many employees have an age key/value pair? 

// What's the sum of the ages, if the value does not exist use 0 

assert message.employees.sum { it.age==null?0:it.age } == 6 // Could I use some sort of null check? 
assert message.employees.age.sum() == 6 // Is there a way to specify the default value 

回答

3

爲先,

// How many employees have an age key/value pair? 
assert message.employees.findAll { it.age }.size() == 2 
// Or 
assert message.employees.age.findAll().size() == 2 

而對於總和:

// You could use the elvis operator 
assert message.employees.sum { it.age ?: 0 } == 6 
+0

尼斯@tim_yates – pczeus