如何在Groovy中自定义JSONBuilder结果?

时间:2014-11-13 18:01:28

标签: groovy

以下Groovy代码生成当前结果下显示的结果。如何自定义JSON输出,如预期输出

中所示
def resultset = Sql.newInstance(...).rows('select * from client')
println new JsonBuilder(clients:resultset).toPrettyString()

当前结果

{
    "clients": [
        {
            "ID": 1,
            "NAME": "ABC",
            "ADDR1": "123 MAIN ST",
            "ADDR2": "NEW YORK",
            "ZIP": "12345"
        },
        {
            "ID": 2,
            "NAME": "XYZ",
            "ADDR1": "321 MAIN ST",
            "ADDR2": "NEW JERSEY",
            "ZIP": "98761"
        }
    ]
}

我是否需要遍历每一行并自定义?

预期

{
    "clients": [
        {
            "ID": 1,
            "NAME": "ABC",
            "CONTACT": {
                "ADDR1": "123 MAIN ST",
                "ADDR2": "NEW YORK",
                "ZIP": "12345"
            }
        },
        {
            "ID": 2,
            "NAME": "XYZ",
            "CONTACT": {
                "ADDR1": "321 MAIN ST",
                "ADDR2": "NEW JERSEY",
                "ZIP": "98761"
            }
        }
    ]
}

1 个答案:

答案 0 :(得分:2)

下面的代码应该有效(但我不确定是否因为没有提供完整的示例):

println new JsonBuilder(clients:resultset.collect {[
   ID: it.ID,
   NAME: it.NAME,
   CONTACT: [
      ADDR1: it.ADDR1,
      ADDR2: it.ADDR2,
      ZIP: it.ZIP,
   ],
]}).toPrettyString()

尝试一下,如有任何问题请告诉我。你明白它是如何运作的吗?