我怎样才能从json中查询where子句

时间:2014-03-17 04:57:59

标签: c# json linq-to-objects

我试图从我的json查询中返回json部分,其中某个属性具有值。代码:

  class Program
    {
        static void Main(string[] args)
        {
            go();
        }

        public static void go()
        {
            string json = @"{
    'rows': [
        {
            'country': 'UK',
            'description': 'this is a desc',
            'gezien': true,
            'Count': 3,
            'url': 'een/twee',
            'stam': 'blabla',
            'kanaal': 'NOS'
        },
        {
            'url': 'drie/vier',
            'stam': 'divers',
            'Count': 1,
            'kanaal': 'SRV'
        }

    ],
    'skip': 0,
    'take': 10,
    'total': 100
}";
            JObject jObj = JObject.Parse(json);
            var url = (string)jObj.Descendants()
                        .OfType<JProperty>()
                        .Where(p => p.Count > 2)
                        .First()
                        .Value;


            Console.WriteLine(url);
        }


    }

我正在尝试返回具有Count&gt; 2的行,但收到​​此错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll

2 个答案:

答案 0 :(得分:1)

试试这个:

var url = jObj.SelectToken("rows")
              .Where(t => t["Count"].Value<int>() > 2)
              .First()["url"].Value<string>();

答案 1 :(得分:0)

所有jproperties的长度均为1。

您的错误来自

.Where(p => p.Count > 2).First()  // same as First(p => p.Count > 2)
相关问题