Parse JSON String into List

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


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 12:48

    Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

    If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

    var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();
    
    var firstNames = list.Select(p => p.FirstName).ToList();
    var lastNames = list.Select(p => p.LastName).ToList();
    

    Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

提交回复
热议问题