Skip to main content
 首页 » 编程设计

c#之使用正则表达式或 JSON 提取数据

2024年04月12日38yyy_WW

我有以下 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","refs":"52833271","complete":false},{"prediction":"76B Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL","refs"

它在 PHP 中尝试使用 json_decode() 并使用 Regex 我可以正确提取所有数据。

76A Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL \n 76B Fonthill Road, Aberdeen, Aberdeenshire, AB11 6UL \n*

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

请您参考如下方法:

创建一组与您的 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);