andruhovski icon

Json Deserialization Example

andruhovski | PRO | 12/09/17 06:40:20 PM UTC | 0 ⭐ | 625 👁️ | Never ⏰ | []
C# |

1.71 KB

|

None

|

0 👍

/

0 👎

[DataContract]
    public class Forex
    
{
        [DataMember]
        public string symbol { get; set; }
        [DataMember]
        public double price { get; set; }
        [DataMember]
        public double bid { get; set; }
        [DataMember]
        public double ask { get; set; }
        [DataMember]
        public int timestamp { get; set; }
    }
}        
 
//-----------------------------
class Program{
private static void Demo()
        {
            HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("put-url-here");
            httpWReq.Method = "GET";
            httpWReq.ContentType = "application/json";
            httpWReq.Timeout = 300000;
            HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
            List<Forex> jsonResponse = null;
 
            try
            {
                //Get the stream of JSON
                Stream responseStream = httpWResp.GetResponseStream();
 
                //Deserialize the JSON stream
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string r = reader.ReadToEnd();
 
                    //Deserialize our JSON
                    DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Forex>));
                    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(r));
                    jsonResponse = (List<Forex>)sr.ReadObject(ms);
                }
            }
            //Output JSON parsing error
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("Loaded items {0}", jsonResponse.Count);
        }
}

Comments