在 C# 中使用正则表达式从 json 响应中提取值

extract value from json response using regular expression in c#

我正在使用 visual studio 2013 对 Web 应用程序进行 Web 性能测试,我想从 JSON 响应中获取一个值以在另一个请求中使用它。下面是 JSON 结果 \B

"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 部分

我通过构建自定义提取规则来获取 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;
                    }
            }
        }

如果您在内部数组中需要的值和此处的 ArrayName 参数为 'Result',则必须将 UseArrayResult 参数发送为 true。但是如果您需要的值直接存在,那么您必须将 UseArrayResult 参数发送为 false