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

后端 未结 1 1676
旧时难觅i
旧时难觅i 2021-01-03 09:38

I am trying to use the Newtonsoft.Json.Net in c#. The following is part of JSON file that I need to retrieve data out of:

{
    \"video\":{
        \"local_r         


        
相关标签:
1条回答
  • 2021-01-03 10:37

    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"]);
    
    0 讨论(0)
提交回复
热议问题