2017-07-25 49 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