Groovy

2016-03-21 25 views
1

içinde JSON'da null veya eksik anahtar/değer çiftiyle çalışma Aşağıdaki kod, değerlendirmeye çalıştığım bir örnek JSON'u gösterir.Groovy

Yumruk 2 ifadesi ifadeleri işe yarar, ancak gerisi işe yaramaz. Herhangi bir yardım harika olacaktır.

Kodu: İlk For

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 

cevap

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 

Ve

toplamı için:

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

Güzel @tim_yates – pczeus