0

我将从我的项目列表中创建简单的 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)

但是,我想在闭包中实现这一点。

4

2 回答 2

1

您建议的代码生成[[name:Guillaume, code:R3VpbGxhdW1l], [name:Jochen, code:Sm9jaGVu], [name:Paul, code:UGF1bA==]],所以您的代码就可以了吗?看来您的环境正在阻止此脚本。

于 2017-05-11T08:14:29.347 回答
0

您可以使用 GString 创建 base64 字符串:

import groovy.json.JsonBuilder

def json(items) {
    def builder = new JsonBuilder()

    builder(items.collect { item ->
        [ 
            name: item.name, 
            code: "${item.name.bytes.encodeBase64()}"
        ]
    })
    builder.toString()
}

def authors = [
    [ name: "John Doe" ]
]


assert json(authors) == '[{"name":"John Doe","code":"Sm9obiBEb2U="}]'
于 2017-05-10T17:00:20.857 回答