如何使用正则表达式规则从json数据响应中检索值?

时间:2016-03-14 03:57:14

标签: c# json regex

根据我从回复中收到的内容,我很难阅读我的正则表达式匹配。任何人都可以指导我如何使用正则表达式为以下json格式工作?

 HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            myReq.ContentType = "application/json";

            // here's how to set response content type:
            Response.ContentType = "application/json"; // that's all

            var response = (HttpWebResponse)myReq.GetResponse();
            string text;

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                text = sr.ReadToEnd();
            }

            MatchCollection nameCollection = Regex.Matches(text, @"<_id>\s*(.+?)\s*</_id>", RegexOptions.Singleline);
            MatchCollection postalCollection = Regex.Matches(text, @"<postal_code>\s*(.+?)\s*</postal_code>", RegexOptions.Singleline)
            MatchCollection schoolCollection= Regex.Matches(text, @"<all_schools_2016>\s*(.+?)\s*</postal_code>,", RegexOptions.Singleline);

文字

  

{ “帮助”:   “https://data.gov.sg/api/3/action/help_show?name=datastore_search”,   “success”:true,“result”:{“resource_id”:   “36e6b5fc-9acc-4344-8f5f-5f67d52c525f”,“fields”:[{“type”:“int4”,   “id”:“_ id”},{“type”:“text”,“id”:“all_schools_2016”},{“type”:   “text”,“id”:“address”},{“type”:“numeric”,“id”:“postal_code”}],   “records”:[{“_ id”:1,“postal_code”:“738907”,“all_schools_2016”:   “ADMIRALTY PRIMARY SCHOOL”,“地址”:“11 WOODLANDS CIRCLE”},{“_ id”:   2,“postal_code”:“737916”,“all_schools_2016”:“ADMIRALTY SECONDARY   学校“,”地址“:”31 WOODLANDS CRESCENT“},{”_ id“:3,   “postal_code”:“768643”,“all_schools_2016”:“AHMAD IBRAHIM PRIMARY   学校“,”地址“:”10 YISHUN STREET 11“},{”_ id“:4,”postal_code“:   “768928”,“all_schools_2016”:“AHMAD IBRAHIM中学”,   “地址”:“751 YISHUN AVENUE 7”},{“_ id”:5,“postal_code”:“579646”,   “all_schools_2016”:“爱童学校”,“地址”:“100 Bright Hill   驱动器“}],”_ links“:{”start“:   “?/ API /动作/ datastore_search极限= 5&安培; RESOURCE_ID = 36e6b5fc-9acc-4344-8f5f-5f67d52c525f”,   “下一个”:   “/ API /动作/ datastore_search偏移= 5&安培;极限= 5&安培; RESOURCE_ID = 36e6b5fc-9acc-4344-8f5f-5f67d52c525f”},   “限制”:5,“总计”:367}}

1 个答案:

答案 0 :(得分:0)

为什么你需要这个任务的正则表达式?

使用JSON.NET

string json = "...";
dynamic data = JsonConvert.DeserializeObject(json);
if((bool)data.success)
{
     IEnumerable<dynamic> records = data.result.records;

     IEnumerable<int> names = records.Select(r => (int)r._id);
     IEnumerable<string> postal = records.Select(r => (string)r.postal_code);
     IEnumerable<string> schools = records.Select(r => (string)r.all_schools_2016);
}