2017-07-15 285 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