使用JSONPath或SelectTokens查询JSON?使用C#中的JSON.NET

时间:2015-06-12 13:25:32

标签: json json.net querying

我正在尝试在c#中使用Newtonsoft.Json.Net。以下是我需要从以下位置检索数据的JSON文件的一部分:

{
    "video":{
        "local_recording_device":{
            "codecs":null
        },
        "preferred_string":"___PREFERRED___",
        "streams":{
            "99176901":{
                "id":"99176901",
                "name":"PTZ Camera",
                "site":"someone",
                "email":"someone@awebsite.com",
                "codec":"VP8 HD1 (720p)",
                "local":true,
                "screen":false,
                "fit_to_window":true,
                "stay_on_top":false,
                "layout":0,
                "native_width":1280,
                "native_height":720,
                "window_width":456,
                "window_height":254,
                "preferred":false,
                "local_recording":false,
                "device_id":"MJPEG Camera",
                "normalized_device_id":"MJPEGCamera",
                "shared_window_id":"MJPEG Camera",
                "enable":true,
                "big_location":"2",
                "x":347,
                "y":737,
                "window_id":"197302",
                "camera_id":null
            },
            "3091494011":{
                "id":"3091494011",
                "name":"Logitech Webcam C930e",
                "site":"Joe Smith",
                "email":"joe@awebsite.com",
                "codec":"VP8 Medium (CIF)",
                "local":false,
                "screen":false,
                "fit_to_window":true,
                "stay_on_top":false,
                "layout":0,
                "native_width":352,
                "native_height":288,
                "window_width":864,
                "window_height":702,
                "preferred":true,
                "local_recording":false,
                "enable":true,
                "big_location":"1",
                "x":204,
                "y":0,
                "window_id":"197296",
                "camera_id":null
            },
            "3798287599":{
                "id":"3798287599",
                "name":"Drive Camera",
                "site":"ASiteName",
                "email":"asitesame@awebsite.com",
                "codec":"VP8 HD1 (720p)",
                "local":true,
                "screen":false,
                "fit_to_window":true,
                "stay_on_top":false,
                "layout":0,
                "native_width":1280,
                "native_height":720,
                "window_width":456,
                "window_height":254,
                "preferred":true,
                "local_recording":false,
                "device_id":"Logitech Webcam C930e",
                "normalized_device_id":"LogitechWebcamC930e",
                "shared_window_id":"Logitech Webcam C930e",
                "enable":true,
                "big_location":"3",
                "x":814,
                "y":737,
                "window_id":"262822",
                "camera_id":null
            }
        }
    }
}

因此,在JSON数据内部是:“视频”,流内的“流”可以是x量不同的流(流ID)。 “流”中的流(长数)可以随时改变。在我的例子中有三个。我需要在“流”中搜索所有流,并查看它们中是否有任何一个与特定电子邮件地址匹配的“电子邮件”。每个流都有一个“电子邮件”。如果电子邮件与我提供的电子邮件地址匹配,我需要检查流“启用”以查看它是真还是假。

任何帮助都会引导我朝着正确的方向前进。我之前没有使用过JSON数据。

1 个答案:

答案 0 :(得分:5)

您可以使用LINQ to JSONSelectTokens来执行所需的查询:

        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();

如果启用了所需电子邮件的第一个流,则查询返回true falsenull,如果该电子邮件没有流,则返回enabled地址。

请注意,这会返回与给定电子邮件地址匹配的第一个流的 var anyEnabled = streamQuery.Any(s => (bool)s["enable"]); 状态。如果您想知道是否启用了任何,请执行以下操作:

function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message,$unique_filename)
{
    try
    {


        $fileName = $unique_filename.".pdf";

        $postdata =  array('OutputFileName' => $fileName, 'ApiKey' => $apiKey, 'file'=>"@".$fileToConvert);
        $ch = curl_init("http://do.convertapi.com/word2pdf");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $result = curl_exec($ch); 
        $headers = curl_getinfo($ch);

        $header=ParseHeader(substr($result,0,$headers["header_size"]));
        $body=substr($result, $headers["header_size"]);

        curl_close($ch);
        if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 ) 
        {
            // Check for Result = true

            if (in_array('Result',array_keys($header)) ?  !$header['Result']=="True" : true)
            {
                $message = "Something went wrong with request, did not reach ConvertApi service.<br />";
                return false;
            }
            // Check content type 
            if ($headers['content_type']<>"application/pdf")
            {
                $message = "Exception Message : returned content is not PDF file.<br />";
                return false;
            }
            $fp = fopen($pathToSaveOutputFile.$fileName, "wbx");

            fwrite($fp, $body);

            $message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
            return true;
        }
        else 
        {
         $message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
         return false; 
        }
    }
    catch (Exception $e) 
    {   
        $message = "Exception Message :".$e.Message."</br>";
        return false; 
    }
}