1

Groovyを初めて使用し、配列をJSONに変換するのに問題があります。計算されたJSONには、配列リストのすべての値が含まれているはずですが、最後の値のみが格納されています。コードは次のとおりです。

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/

期待される出力は次のとおりです。

{
"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
            }
        ]
    }
]
}
4

1 に答える 1

7

このようなものはあなたが望む結果を与えるようです:

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()
于 2012-05-24T14:33:11.293 に答える