2014-10-02 27 views
0

實施例從groovy ws-lite git hub project.如何使用groovy創建一個json數組?

採取(的思想)說我有下面的代碼塊來發送一個RESTful post請求:

void 'Holiday Service get holidays by country, year and month'() { 
    given: 
    def client = new RESTClient('http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx') 
    when: 
    def response = client.post(path: '/GetHolidaysForMonth') { 
     type ContentType.JSON 
     json files: ['spec_test.txt':[content: "2014-12-12"]] 
    } 

    then: 
    200 == response.statusCode 
    'text/xml' == response.contentType 
    'Christmas' == response.xml 
      .Holiday 
      .find { it.HolidayCode.text() == 'CHRISTMAS-ACTUAL'} 
      .Descriptor.text() 
} 

這裏是什麼在請求體中產生:

{"files":{"spec_test.txt":{"content":"2014-12-12"}}} 

如何更改代碼來生成此json數組:

[{"files":{"spec_test.txt":{"content":"2014-12-12"}}}] 

注意下面的代碼可以做的伎倆:

def sampleRequest = '[{"files":{"spec_test.txt":{"content":"2014-12-12"}}}]' 
def jsonArray = new JsonSlurper().parseText(sampleRequest) 

void 'Holiday Service get holidays by country, year and month'() { 
    given: 
    def client = new RESTClient('http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx') 

    when: 
    def response = client.post(path: '/GetHolidaysForMonth') { 
     type ContentType.JSON 
     json jsonArray 
    } 

    then: 
    200 == response.statusCode 
    'text/xml' == response.contentType 
    'Christmas' == response.xml 
       .Holiday 
       .find { it.HolidayCode.text() == 'CHRISTMAS-ACTUAL'} 
       .Descriptor.text() 
} 

但我想知道是否有另一種方式來做到這一點?

回答

0

至於我深知你只需要替換下面的行:

files: ['spec_test.txt':[content: "2014-12-12"]] 

這一個:

[[files: ['spec_test.txt':[content: "2014-12-12"]]]] 

它只是通過一個列表,而不是地圖json關鍵,但雙方括號是必要的,因爲一對將是使用來表示地圖和第二個創建名單

+0

嗨歐泊,謝謝你的回答。我得到了以下錯誤: groovy.lang.MissingPropertyException:沒有這樣的屬性:json的類:wslite.rest.ContentBuilder – nzsquall 2014-10-02 19:23:48

+0

這似乎是一個不同的問題。它之前運行良好嗎?你只做了我在答案中提到的更改? – Opal 2014-10-02 19:48:02

+0

它在工作之前,我做出了唯一改變你的答案。 – nzsquall 2014-10-02 21:26:02