Parse JSON String into List

后端 未结 5 2114
借酒劲吻你
借酒劲吻你 2021-02-14 11:55
string json = \"{\\\"People\\\":[{\\\"FirstName\\\":\\\"Hans\\\",\\\"LastName\\\":\\\"Olo\\\"}
                            {\\\"FirstName\\\":\\\"Jimmy\\\",\\\"LastName\         


        
5条回答
  •  臣服心动
    2021-02-14 12:59

    Seems like a bad way to do it (creating two correlated lists) but I'm assuming you have your reasons.

    I'd parse the JSON string (which has a typo in your example, it's missing a comma between the two objects) into a strongly-typed object and then use a couple of LINQ queries to get the two lists.

    void Main()
    {
        string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";
    
        var result = JsonConvert.DeserializeObject(json);
    
        var firstNames = result.People.Select (p => p.FirstName).ToList();
        var lastNames = result.People.Select (p => p.LastName).ToList();
    }
    
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    public class RootObject
    {
        public List People { get; set; }
    }
    

提交回复
热议问题