2016-12-13 223 views
1

我有json格式的以下數據。使用正則表達式或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」, 「完成」:假},{ 「預測」: 「76B特希爾道,香港仔,阿伯丁,AB11 6UL」, 「裁判」

它與json_decode()試圖在PHP中使用正則表達式我可以正確提取所有數據。

76A特希爾道,香港仔,阿伯丁,AB11 6UL \ n 76B特希爾道,香港仔,阿伯丁,AB11 6UL \ n *

我需要爲C#的解決方案。

+1

它應該是比較簡單的#拉的數據用C出與JSON.NET。你能發佈你試過的代碼嗎? – Tim

+0

感謝蒂姆,我在我的代碼中犯了一個錯誤,但我對C#很陌生,我花了幾個小時,發現拼寫爲Prediciton的Prediction。 –

回答

3

創建一組與您的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); 
+0

謝謝Seminda,我的代碼與你非常相似,非常感謝你的幫助。 –