如何获取json响应的子节点数据

时间:2018-05-19 17:36:41

标签: c# json onem2m

我有一个M2M api。它提供了json响应。因为我需要在C#字符串变量中存储一个子节点信息。我在变量中得到空值。我想得到con节点的dataFrame数据。

json数据

{
    "m2m:cin": {
        "ty": 4,
        "ri": "IoT/15a395/default/d37b4b81f9e",
        "pi": "IoT/15a395/default",
        "ct": "20180519T141254,000665",
        "lt": "20180519T141254,000665",
        "rn": "d37b4b81f9e",
        "et": "20280516T141254,000664",
        "st": 1,
        "cr": "C7AACE9CB",
        "cnf": "application/json",
        "cs": 798,
        "con": "{\"userid\":\"user1\",\"payloads_ul\":{\"id\":1526738533510,\"snr\":0,\"fcnt\":1166,\"freq\":865403015.1367188,\"live\":false,\"port\":2,\"rssi\":-99,\"deveui\":\"15a395\",\"cr_used\":\"4/5\",\"devaddr\":4262830997,\"dr_used\":\"SF12BW125\",\"sf_used\":12,\"gtw_info\":null,\"dataFrame\":\"QUxJVkUqQkFUMzUw\",\"decrypted\":true,\"timestamp\":\"2018-05-19T14:02:13.510Z\",\"time_on_air_ms\":1155.0720000000001,\"device_redundancy\":1}}"
    }
}

 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url");
                req.Method = "GET";
                req.Headers["Authorization"] = "Basic " + "QzdBQUNFOUN";
                req.ContentType = "application/vnd.onem2m-res+json";
                req.Accept = "application/vnd.onem2m-res+json;";
                req.Headers["Cache-Control"] = "no-cache";
                req.Headers["X-M2M-RI"] = "9900001";
                req.Headers["X-M2M-Origin"] = "C7AACE9-73";
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                var encoding = resp.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet);

                using (var stream = resp.GetResponseStream())
                {
                   var reader = new StreamReader(stream, encoding);
                var responseString = reader.ReadToEnd();
                dynamic bin = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString);
                byte[] data = Convert.FromBase64String(bin.dataFrame.ToString());
                }

1 个答案:

答案 0 :(得分:0)

您有两个选项,为响应建模或使用动态对象。我个人更喜欢将对象建模为类型并反序列化。您不必为整个对象建模,只需要您想要访问的内容。

class m2m_cin {
    public string con { get; set; }
}

var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, m2m_cin>>(responseString);
string con_raw = resp["m2m:cin"].con;

现在您需要做的就是重复con_raw的反序列化,然后访问您想要的属性。