Groovy:将数组转换为JSon [英] Groovy: Convert Array to JSon

查看:245
本文介绍了Groovy:将数组转换为JSon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy是新手,并且无法将数组转换为JSON。计算的JSON应该包含我的数组列表中的所有值,但它只存储最后一个值。这里是代码:

Am new to Groovy and am having trouble converting an array to JSON. The JSON computed should have all the values from my array list, but it is storing only the last one. Here is the code:

def arraylist = [["0",2],["1",8],["2",6],["3",8],["4",3]]

def arraysize = arraylist.size()

def builder = new groovy.json.JsonBuilder()
 builder ({
       cols([
                {
                    "id" "hours"
                    "label" "Hours"
                    "type" "string"
                },
                {
                    "id" "visitor"
                    "label" "Visitors"
                    "type" "number"
                }
           ])

         rows([
                {
                        for( i in 0..< arraysize )
                        {
                        c([
                             {
                                 "v" arraylist[i][0]
                             },
                             {
                                 "v" arraylist[i][1]
                             }
                         ])
                        }//for

                }
           ])
})

println builder.toPrettyString()

可以尝试在这里运行代码:
http://groovyconsole.appspot.com/

Can try running the code here: http://groovyconsole.appspot.com/

预期输出在这里:

{
"cols": [
    {
        "id": "hours",
        "label": "Hours",
        "type": "string"
    },
    {
        "id": "visitor",
        "label": "Visitors",
        "type": "number"
    }
],
"rows": [
    {
        "c": [
            {
                "v": "0"
            },
            {
                "v": 2
            }
        ]
    },
    {
        "c": [
            {
                "v": "1"
            },
            {
                "v": 8
            }
        ]
    },
    {
        "c": [
            {
                "v": "2"
            },
            {
                "v": 6
            }
        ]
    },
    {
        "c": [
            {
                "v": "3"
            },
            {
                "v": 8
            }
        ]
    },
    {
        "c": [
            {
                "v": "4"
            },
            {
                "v": 3
            }
        ]
    }
]
}


推荐答案

类似这样的东西似乎给出了您想要的结果:

Something like this seems to give the result you wanted:

def arraylist = [["0",2],["1",8],["2",6],["3",8],["4",3]]

def builder = new groovy.json.JsonBuilder()
builder {
  cols( [
    [ id: "hours",   label: "Hours",    type: "string" ],
    [ id: "visitor", label: "Visitors", type: "number" ] ] )

  rows( arraylist.collect { pair -> [ c: pair.collect { item -> [ v: item ] } ] } )
}

println builder.toPrettyString()

这篇关于Groovy:将数组转换为JSon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆