【问题标题】:C# Regex matching JSON api response correctlyC# Regex 正确匹配 JSON api 响应
【发布时间】:2016-07-13 14:23:18
【问题描述】:

我正在尝试以正确的方式匹配 Blockchain JSON Api 响应,但似乎我做不到。区块链 API 响应如下所示:

{
    "addresses": [
        {
            "balance": 1400938800,
            "address": "1Q1AtvCyKhtveGm3187mgNRh5YcukUWjQC",
            "label": "SMS Deposits",
            "total_received": 5954572400
        },
        {
            "balance": 79434360,
            "address": "1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq",
            "label": "My Wallet",
            "total_received": 453300048335
        },
        {
            "balance": 0,
            "address": "17p49XUC2fw4Fn53WjZqYAm4APKqhNPEkY",
            "total_received": 0
        }
    ]
}

基本上,如您所见。对于每个地址,C# ReadToEnd() 上的每一行都让我搞砸了。但基本上我正在尝试,如果有标签 SMS Deposits 示例,那么从“那条线”它将采用该地址,没有其他地方。示例:标签是彼得,那么它只从彼得行获取地址,而不是任何其他行。我怎么能那样做?这也是我的代码:

    listAddresses.Method = "GET";
    HttpWebResponse listAddressesResp = (HttpWebResponse)listAddresses.GetResponse();
    StreamReader listAddressesSR = new StreamReader(listAddressesResp.GetResponseStream());
    var resultListAddresses = listAddressesSR.ReadToEnd();
    if (resultListAddresses.Contains(name))
    {
        Regex SuiWillThatWork = new Regex("\"address\":\"[A-Za-z0-9]+");
        var TestingVol2 = SuiWillThatWork.Match(resultListAddresses).Value;
        TestingVol2 = TestingVol2.Replace("\"address\":\"", "");
        address = TestingVol2;
        MessageBox.Show(resultListAddresses);
        MessageBox.Show(address);
    }

【问题讨论】:

  • XY 问题?与其破解它来工作,不如去获取Newtonsoft.Json 并按应处理的方式处理 JSON。
  • 是的,好的。如果我以正确的方式“对待”它,那么仍然......我如何从那个“行/块”中正则表达式该信息
  • 如果您将其视为 JSON,则绝对没有理由继续使用 RegEx。即使你确实让它与正则表达式一起工作,1)它会很脆弱,可能不会在任何情况下都工作,2)如果供应商更改 API/响应,脆弱尤其如此,3)已经有一个解析器——使用它。

标签: c# json regex


【解决方案1】:

不要将正则表达式用于已经开发了非常好的解析器的东西。去帮自己一个忙,Install-Package Newtonsoft.Json 并尝试以下操作:

首先,建立与返回的响应相匹配的对象。如果您很懒惰,可以使用一些工具(例如json2csharp.com)来简化此操作。对于您的回复,如下所示:

class ServerResponse
{
    [JsonProperty("addresses")]
    public List<AddressResponse> Addresses { get; set; }
}
class AddressResponse
{
    [JsonProperty("balance")]
    public long Balance { get; set; }
    [JsonProperty("address")]
    public string Address { get; set; }
    [JsonProperty("label")]
    public string Label { get; set; }
    [JsonProperty("total_received")]
    public long TotalReceived { get; set; }
}

注意:您不必采用 JsonPropertyAttribute 的方式,但我喜欢让我的模型遵循命名约定。

接下来,我们需要将响应反序列化为我们的新对象。使用 Newtonsoft,很简单:

var response = JsonConvert.DeserializeObject<ServerResponse>(jsonResponse);

你现在有一个完全水合的物体:

ServerResponse
  Addresses (List<AddressResponse> (3 items))
    Balance     Address                            Label         TotalReceived
    1400938800  1Q1AtvCyKhtveGm3187mgNRh5YcukUWjQC SMS Deposits  5954572400 
    79434360    1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq My Wallet     453300048335 
    0           17p49XUC2fw4Fn53WjZqYAm4APKqhNPEkY null          0 

回到手头的问题,现在我们可以查找“短信存款”并检索地址:

var response = JsonConvert.DeserializeObject<ServerResponse>(jsonResponse);
var smsDeposits = response.Addresses.FirstOrDefault(x => x.Label == "SMS Deposits");
if (smsDeposits != null)
{
   MessageBox.Show(smsDeposits.Address);
}

【讨论】:

  • 感谢您抽出宝贵时间帮助我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-08-12
  • 2013-07-23
  • 1970-01-01
  • 2020-09-01
相关资源
最近更新 更多