2017-07-15 288 views
0

我正在使用visual studio 2013爲web應用程序執行web性能測試,並且我想從JSON響應中獲取值以在另一個請求中使用它。下面是JSON結果\乙從c#中使用正則表達式提取json響應的值

"ResultMessage": 
    "Success","Result":{"IsAnonymous":false, 
      "DestinationBranchID":"5886c018-0a74-42c0-a334-f221beacdd49", 
      "ID":"83f65759-a442-4dbf-8772-550e5dec7933", 
      "No":943514207446, 
      "DestinationCityID":"43694b12-9c32-49d8-8e02-7663bbf7e07b", 
      "IssueDateTime":"2017-07-15T11:24:38", 
      "Amount":1500.0000, 
      "IsFeeIncluded":false, 
      "NetFee":200.0000, 
      "PayAtCashier":1700.0000, 
      "CustomerIdentityID":"f62c2def-04d8-46e6-a501-5c95423a4292", 
      "ReasonID":"00000000-0000-0000-0000-000000000000", 
      "BenefactorName":null, 
       "BenefactorPhone":null, 
       "BenefactorMobile":null, 
       "BeneficiaryName":"Test", 
       "BeneficiaryPhone":"09918367343", 
       "BeneficiaryMobile":"011686383", 
       "Note":"", 
       "RowVersion":"AAAAAAAAVp4="}} 

我想要得到的ID字段的值,我想這正則表達式\ 「ID \」:\ 「*。?」 但它給了我整個「ID」:「83f65759-a442-4dbf-8772-550e5dec7933」,但我只需要Guid部分

+0

您是否嘗試過使用捕獲組? '\「ID \」:\「(。*?)」'從比賽中獲得第1組? [在這裏你會找到一個例子](https://www.dotnetperls.com/regex-groups) – LukStorms

回答

1

我解決了它通過構建自定義提取規則來獲取JSON列的值,

public string Name { get; set; } 

    public bool UseArrayResult { get; set; } 

    public string ArrayName { get; set; } 

    public override void Extract(object sender, ExtractionEventArgs e) 
    { 
     if (e.Response.BodyString != null) 
     { 
      var json = e.Response.BodyString; 
      var data = JObject.Parse(json); 
      if (!UseArrayResult) 
      { 
       if (data != null) 
       { 
        e.WebTest.Context.Add(this.ContextParameterName, data.SelectToken(Name)); 
        e.Success = true; 
        return; 
       } 
      } 
      else 
      { 
       var result = data[ArrayName]; 
        if (result != null) 
        { 
         e.WebTest.Context.Add(this.ContextParameterName, result.SelectToken(Name)); 
         e.Success = true; 
         return; 
        } 
      } 
     } 

你要發送UseArrayResult帕拉姆爲true,如果值你所需要的內部陣列和arrayName中的帕拉姆這裏「結果」內。但如果您需要的值直接存在,則必須將UseArrayResult參數發送爲false