繁体   English   中英

如何使用循环从c#中的字符串中提取特定的子字符串?

[英]how do I extract a specific substring from a string in c# using a loop?

我试图从我从Web服务器得到的响应中仅提取路由号。 响应看起来像这样;

[{“ Description”:“ METRO Blue Line”,“ ProviderID”:“ 8”,“ Route”:“ 901”},{“ Description”:“ METRO Green Line”,“ ProviderID”:“ 8”,“ Route “:” 902“},

我所需要的只是获取路由号,以便我用它们填充组合框。 我正在尝试使用循环,因为有很多循环。 我当前的解决方案获得了第一个路由号,但是由于某种原因,我仅获得了之后的提供商号,这就是我到目前为止的结果。

        //get bus routes and popluate the busRoutecmb
        restClient.endPoint = routeUrl + formatLine;
        string response = restClient.request();

        //show me what was returned for debug puposes
        System.Diagnostics.Debug.Write(response);

        //sort through data and put relevent item in a list
        List<string> responseItems = new List<string>();
        //splitting into routes
        string[] splitByRoute = response.Split('}');

        //extracting route number from elements in splitByRoute
        List<string> extractedRouteNums = new List<string>();

        foreach (string thing in splitByRoute)
        {
            //splitting each bus route up by piece of information
            string[] splitByWord = thing.Split(',');
            //getting rid of everything but the route number
            int length = splitByWord.Length;
            int count = 2;
            while (count <= length)
            {
                string[] word = splitByWord[count].Split(':');
                string routeNum = word[1].Trim('"');
                count += 3;
                extractedRouteNums.Add(routeNum);
                System.Diagnostics.Debug.WriteLine(count);
                System.Diagnostics.Debug.WriteLine(routeNum);

            }

        }

        //add repsonse to busRoutecmb
        busRoutecmb.DataSource = extractedRouteNums;

    }

您得到的基本上是一个JSON字符串,它只是一个名称值对数组或一个Dictionary List。

  [{
        "Description": "METRO Blue Line",
        "ProviderID": "8",
        "Route": "901"
    },
    {
        "Description": "METRO Green Line",
        "ProviderID": "8",
        "Route": "902"
    }]

您可以通过几种方式将该字符串反序列化为List,一种是使用System.Web.Script.Serialization.JavaScriptSerializer或JSON.NET。 进入列表后,您可以查询该列表并仅返回路由键,值对。

    var data = "[{ Description:\"METROBlueLine\",ProviderID:\"8\",Route:\"901\"},{Description:\"METRO Green Line\",ProviderID:\"8\",Route:\"902\"}]";

                var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
                var mylist = ser.Deserialize<List<Dictionary<string,string>>>(data);
    //or JSON.net
                var mylist = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var routes = mylist.SelectMany(a => a).Where(c => c.Key == "Route").ToList();
                foreach (var route in routes)
                    Console.Write(route);

    output
    [Route, 901][Route, 902]

如果您真的只想要这些值,那么

var routesonly = routes.Select(r => r.Value).ToList();

Gratzy认为这是JSON是正确的,但我建议您使用JSON.NET对其进行反序列化。

var items = JsonConvert.DeserializeObject<JArray>(response);
var routeNumbers = items.Select(i => i.Value<string>("Route")).ToList();

您还可以使用http://json2csharp.com/生成一个强类型模型,并根据需要反序列化为该模型类型。

public class RootObject
{
    public string Description { get; set; }
    public string ProviderID { get; set; }
    public string Route { get; set; }
}

var items = JsonConvert.DeserializeObject<RootObject[]>(response);
var routeNumbers = items.Select(i => i.Route).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM