如何使用groovy创建json数组?

时间:2014-10-02 04:18:37

标签: json groovy

取自groovy ws-lite git hub project.

的例子(想到)

假设我有以下代码块来发送RESTful帖子请求:

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()
 } 

但我想知道是否有另一种方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

据我所知,您只需要替换以下行:

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

这一个:

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

它只是传递了一个列表而不是映射到json键,但是需要双方括号,因为一对将使用来表示 map 和第二个创建列表