在任意JSON中的任意位置查找特定元素 [英] Find a specific element anywhere in an arbitrary JSON

查看:315
本文介绍了在任意JSON中的任意位置查找特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON.NET的新手,不确定如何做到这一点.

I am new to JSON.NET and not sure how to do this.

我有 CartItem 类,并且需要实现
GetAllCartItemsFromArbitraryJson(string jsonStr),如下所示:

I have the CartItem class, and I need to implement
GetAllCartItemsFromArbitraryJson(string jsonStr), as follows:

class CartItem {
  public int Id;
  public int Qty;
}

List<CartItem> items = GetAllCartItemsFromArbitraryJson(jsonStr);

我所知道的是 jsonStr 在某个地方包含一个或多个 cartitem (我不知道有多深),例如.

All I know is jsonStr contains one or more cartitems somewhere (I don't know how deep), eg.

{
  ... : {
    "cartitems": [{
        "id": "1",
        "qty": "1"
      },{
        "id": "2",
        "qty": "5"
      }
    ]
  },
  ... : {
    ... : {
      ...,
      "cartitems": [{
          "id": "10",
          "qty": "2"
        }
      ]
    }
  }
}

此功能需要收集所有 cartitems ,并将其放入 List< CartItem>

This function needs to collect all the cartitems and put it in List<CartItem>

List<CartItem> GetAllCartItemsFromArbitraryJson(string jsonStr) {
  JObject json = JObject.Parse(jsonStr);
  // then what...?
}

因此 List< CartItem> 将包含:

Id  Qty
1   1
2   5
10  2

您将如何在C#中做到这一点?

How would you do it in C#?

推荐答案

这是可行的解决方案:

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 :)

这篇关于在任意JSON中的任意位置查找特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆