写一个 json 到字符串

import groovy.json.JsonOutput;

def json = JsonOutput.toJson([foo: 'bar', baz: [1]])

assert json == '{"foo":"bar","baz":[1]}'

除了地图,列表和原语外,groovy.json.JsonOutput 还支持 POJO 序列化:

import groovy.json.JsonOutput; 
 
class Tree { 
    def name
    def type
}

Tree willow = new Tree(name:'Willow',type:'Deciduous')
Tree olive = new Tree(name:'Olive',type:'Evergreen')

assert JsonOutput.toJson(willow) == '{"type":"Deciduous","name":"Willow"}'
assert JsonOutput.toJson([willow,olive]) == '[{"type":"Deciduous","name":"Willow"},{"type":"Evergreen","name":"Olive"}]'