Groovy是一種基于JVM的動態(tài)編程語言,具有很強的腳本和編程能力。Groovy也提供了方便的JSON處理能力,可以輕松的在Groovy中解析和生成JSON數(shù)據(jù)。
在Groovy中,可以使用JsonSlurper類或JsonBuilder類來處理JSON數(shù)據(jù)。JsonSlurper類可以將JSON字符串解析成Groovy的Map或List,而JsonBuilder類則可以將Groovy的Map或List轉(zhuǎn)換成JSON字符串。
// 使用JsonSlurper解析JSON字符串 def json = '{"name": "Tom", "age": 20, "address": {"city": "Beijing", "province": "Beijing"}}' def slurper = new JsonSlurper() def result = slurper.parseText(json) assert result.name == "Tom" assert result.age == 20 assert result.address.city == "Beijing" assert result.address.province == "Beijing"
// 使用JsonBuilder生成JSON字符串 def jsonBuilder = new JsonBuilder() def result = jsonBuilder { name "Tom" age 20 address { city "Beijing" province "Beijing" } } assert result.toString() == '{"name":"Tom","age":20,"address":{"city":"Beijing","province":"Beijing"}}'
Groovy還提供了方便的JSON路徑表達式,可以通過JsonPath類來實現(xiàn)。以下是JsonPath的示例代碼:
// 使用JsonPath查詢JSON數(shù)據(jù) def json = '{"name": "Tom", "age": 20, "address": {"city": "Beijing", "province": "Beijing"}}' def jsonPath = new JsonPath("$.name") def result = jsonPath.read(json) assert result == "Tom" jsonPath = new JsonPath("$.address.city") result = jsonPath.read(json) assert result == "Beijing"
總的來說,Groovy提供了豐富的JSON處理功能,可以輕松的解析和生成JSON數(shù)據(jù),并且可以使用JSON路徑表達式來方便地查詢JSON數(shù)據(jù)。