Search code examples
c#jsononem2m

how to get child node data of the json response


i have oneM2M api . which provides json response. in that i need to store one child node information in the C# string variable. im getting the null value in the variable.i want to get the data of dataFrame of the con node.

json data

{
    "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}}"
    }
}

code

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

Solution

  • You have two options, model the response or use dynamic objects. Personally I prefer to model the objects into types and deserialize. You don't have to model the entire object, just the stuff you want access to.

    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;
    

    Now all you need to do is repeat the deserialization for con_raw and then access the property you wanted.