2017-07-25 44 views
1

我尝试使用SOAP UI和groovy脚本从json收集数据时遇到问题。下面是一个例子JSON:从Json中显示不正确的属性

{ 
    "regions": [{ 
     "hotels": [{ 
       "roomInformation": [{ 
        "hotelRoomId": xxx, 
       }], 
       "regionId": x, 
       "hotelId": xxx,     
       "providerInformation": { 
        "ratePlanCode": "xxx", 
       }, 
       "providerHotelId": 0000001 
      }, 

      { 
       "roomInformation": [{ 
        "hotelRoomId": xx, 
       }], 
       "regionId": x, 
       "hotelId": xxx,     
       "providerInformation": { 
        "ratePlanCode": "ggg", 
       }, 
       "providerHotelId": 0000002 
      } 
     ], 
     "errors": null 
    }], 
    "errors": null 
} 

我想要做的是选择的providerHotelIdratePlanCode第一个实例。要做到这一点,我有以下Groovy脚本来解决这个:

def alert = com.eviware.soapui.support.UISupport 
import groovy.json.JsonSlurper 
def response = testRunner.testCase.getTestStepByName("Search Test").getProperty("Response").getValue(); 

def jsonRes = new JsonSlurper().parseText(response); 

def providerhotelid = jsonRes.regions.hotels.providerHotelId[0].toString() 
def rateplancode = jsonRes.regions.hotels.providerInformation[0].ratePlanCode.toString() 

log.info providerhotelid 

testRunner.testCase.setPropertyValue('providerhotelid', providerhotelid) 
testRunner.testCase.setPropertyValue('rateplancode', rateplancode) 

这低于输出在我的自定义属性:

  • providerhotelid - [0000001,0000002]
  • rateplancode - [XXX]

以上不正确,因为:

  1. providerhotelid - 它显示所有提供商酒店ID,当我只想要第一个应该是0000001
  2. rateplancode - 是正确的,但它显示[]周围,我想这个删除。 providerhotelid也一样。

所以在这个例子中我的自定义属性应显示:

  • providerhotelid - 0000001
  • rateplancode - XXX

这怎么可能我的Groovy脚本中实现?

回答

1

这里是你需要的东西:

//Get all the values, falatten them and get the first one 
def providerhotelid = jsonRes.regions.hotels.providerHotelId.flatten()[0] 
def rateplancode = jsonRes.regions.hotels.providerInformation.ratePlanCode.flatten()[0] 

log.info providerhotelid 
log.info rateplancode 

您可以快速地在线试用Demo

+0

酷,我做到了另一种方式,但将尽可能多的清洁用你的方式。谢谢饶 – BruceyBandit