2012-12-20 106 views
13

我們可以通過生成Groovy的JSON建設者的對象類型JSON:如何使用groovy builder生成一個數組類型的json?

def builder = new groovy.json.JsonBuilder() 
def root = builder.people { 
    person { 
     firstName 'Guillame' 
     lastName 'Laforge' 
     // Named arguments are valid values for objects too 
     address(
       city: 'Paris', 
       country: 'France', 
       zip: 12345, 
     ) 
     married true 
     // a list of values 
     conferences 'JavaOne', 'Gr8conf' 
    } 
} 
def jsonStr = builder.toString() 

我喜歡這種類型的語法,而是如何建立一個數組類型JSON?

E.g.

[ 
    {"code": "111", "value":"222"}, 
    {"code": "222", "value":"444"} 
] 

我發現了一些文件,其中說我們應該用JsonBuilder()構造:

def mydata = [ ["code": "111", "value":"222"],["code": "222", "value":"444"] ] 
def builder = new groovy.json.JsonBuilder(mydata) 
def jsonStr = builder.toString() 

但我更喜歡第一種語法。它能夠使用它生成數組類型的JSON嗎?

回答

7

你提出的語法看起來不太可能,因爲我不相信它是有效的常規。關閉如{"blah":"foo"}對於常規來說沒有意義,並且您將受到語法限制的限制。我認爲你要能夠做到最好的是以下中的東西:

def root = builder.call (
    [ 
     { 
     code "111" 
     value "222" 
     }, 
     {code "222"; value "444"}, //note these are statements within a closure, so ';' separates instead of ',', and no ':' used 
     [code: "333", value:"555"], //map also allowed 
     [1,5,7]      //as are nested lists 
    ] 
) 
0

我喜歡在年底超過建設者轉換,

def json = [ 
      profile: [ 
         _id: profile._id, 
         fullName: profile.fullName, 
         picture: profile.picture 
        ] 
      ,title: title 
      ,details: details 
      ,tags: ["tag1","tag2"] 
      ,internalTags: ["test"] 
      ,taggedProfiles: [] 
      ] as JSON 
+3

我可能是錯的,但我相信JSON轉換器是特定於Grails的。 –

+0

@BriaHenry正確的是,「grails.converters.JSON」 – sumnulu

2

,也可以創建列表關閉並將其傳遞給構建器

import groovy.json.* 

dataList = [ 
    [a:3, b:4], 
    [a:43, b:3, c:32] 
] 
builder = new JsonBuilder() 
builder { 
    items dataList.collect {data -> 
     return { 
      my_new_key '' 
      data.each {key, value -> 
       "$key" value 
      } 
     } 
    } 
} 
println builder.toPrettyString() 
相關問題