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

时间:2018-12-10 20:12:19

标签: c# .net json string-formatting

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

[{“描述”:“ METRO蓝线”,“ ProviderID”:“ 8”,“路线”:“ 901”},{“描述”:“ METRO绿线”,“ ProviderID”:“ 8” ,“路线”:“ 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;

    }

2 个答案:

答案 0 :(得分:0)

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

$obj = new Product($value['id_product']);
$obj->price = (float) $value['base_price'];
if ($value['unity']) {
    $obj->unity = $value['unity'];
    $obj->unit_price = 0;
}

//multistore
if ($value['shops']) {
   //$value['shops'] have string "1,2,3"
   $obj->id_shop_list = explode(',', $value['shops']);
}
$obj->update(); 

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

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

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

    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]

答案 1 :(得分:0)

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();