【问题标题】:Extract data using regex or JSON使用正则表达式或 JSON 提取数据
【发布时间】:2017-04-29 03:46:58
【问题描述】:

我有以下json格式的数据。

{
  "predictions": [
    {
      "prediction": "76A Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL",
      "refs": "52833271",
      "complete": false
    },
    {
      "prediction": "76B Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL",
      "refs": "52833272",
      "complete": false
    }
  ],
  "status": "Ok"
}

我尝试过使用 Json.net 但我无法获取我需要的数据我想要地址

76A Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL

我也尝试过使用

regex Regex Exp = new Regex("\"prediction\":\"(.*),\"refs\""); 

但它匹配

76A Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL","re​​fs":"52833271","complete":false},{"prediction":"76B Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL","re​​fs "

它在 PHP 中使用json_decode() 进行了尝试,使用正则表达式我可以正确提取所有数据。

76A Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL \n 76B Fonthill Road, 阿伯丁, 阿伯丁郡, AB11 6UL \n*

我需要一个 c# 的解决方案。

【问题讨论】:

  • 使用 JSON.NET 将 C# 中的数据提取出来应该相对简单。您可以发布您尝试过的代码吗?
  • 谢谢蒂姆,我在代码中犯了一个错误,但我对 C# 还是很陌生,我花了几个小时才发现我把 Prediction 拼写为 Prediciton。

标签: c# json regex


【解决方案1】:

创建一组与您的 JSON 匹配的类。

 public class Predictions
{
    public string Prediction { get; set; }
    public string Refs { get; set; }
    public bool Complete { get; set; }
}

public class PredictionsList
{
    public List<Predictions> Predictions { get; set; }
    public string Status { get; set; }
}

然后使用JsonConvert反序列化

  var dataDictionary = JsonConvert.DeserializeObject<PredictionsList>(json);

【讨论】:

  • 谢谢Seminda,我的代码和你的很相似,非常感谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2015-02-24
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多