我将从我的项目列表中创建简单的 JSON 数组。我找到了如何使用JsonBuilder来做的很好的示例。看起来像:
class Author {
String name
}
def authors = [new Author (name: "Guillaume"),
new Author (name: "Jochen"),
new Author (name: "Paul")]
def json = new groovy.json.JsonBuilder()
json authors, { Author author ->
name author.name
}
但是,我必须向我的 JSON 添加一个自定义属性。它必须看起来像:
json authors, { Author author ->
def c = author.name.bytes.encodeBase64()
name author.name
code c
}
但是这段代码不起作用,我必须以某种方式将 JSON 成员和闭包成员分开。坦率地说,我不是 groovy 的大专家,我猜这个答案可能有点简单。
另外,我知道我可以创建我的项目的自定义列表并以以下方式转换此列表:
def json = new groovy.json.JsonBuilder(authors)
但是,我想在闭包中实现这一点。