Querying JSON with JSONPath or SelectTokens? With JSON.NET in C#

泪湿孤枕 提交于 2019-12-04 12:55:53

You can use LINQ to JSON and SelectTokens to do the required query:

        string json = GetJson();
        var obj = JObject.Parse(json);
        var testEmail = "someone@awebsite.com";

        var streamQuery = obj.SelectTokens("video.streams.*").Where(s => (string)s["email"] == testEmail);
        var firstEnabled = streamQuery.Select(s => (bool?)s["enable"]).FirstOrDefault();

The query returns a nullable bool that is true or false if the first stream for the desired email is enabled, or null if there is no stream for that email address.

Note that this returns the enabled state of the first stream matching the given email address. If you want to know if any are enabled, do:

        var anyEnabled = streamQuery.Any(s => (bool)s["enable"]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!