且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在任意JSON中的任意位置查找特定元素

更新时间:2023-02-26 17:56:30

这是可行的解决方案:

List<CartItem> GetAllCartItemsFromArbitraryJson(string jsonStr) {
  JObject json = JObject.Parse(jsonStr);

  return json.Descendants().OfType<JProperty>()  // so we can filter by p.Name below
             .Where(p => p.Name == "cartitems")
             .SelectMany(p => p.Value)           // selecting the combined array (joined into a single array)
             .Select(item => new CartItem {
                 Id  = (int)item["id"],
                 Qty = (int)item["qty"]
             }).ToList();
}

希望对别人有帮助.
虽然我是JSON的新手,但是通过试用&获得的.错误.所以让我知道是否可以改进:)

Hope it helps someone.
I am new to JSON though, got that by trial & error. So let me know if it can be improved :)