Tech

Deserializing Complex JSON using C# in 5 minutes.

· 1 min read >

 If have a situation where you immediately need feel a need for DESERIALIZING complex json with c# and save the data into the no SQL database . we are not going to discuss any details on how to save data in mongo database rather we will only focus on de-serializing the incoming JSON.

we used this website http://myjson.com   to save the json which will act as a source of json , in other scenarios the data might be coming in as a response from a webservice request.

we will deserialize this json into the c# class .

Step# 1 Let’s get started with Deserializing Complex JSON using C#. First  Find out the source of JSON – in my case I saved json using myjson.com

Step#2  Generate C# Classes from JSON – I used this website it work pretty well http://json2csharp.com/

Step#3  copy the code generated in previous step and paste in the visual studio – The root Object will be the Top level class.

we can either use a built in Javascript De-Serialize or I would prefer to use Json.NET that is a popular high-performance JSON framework for .NET . It can be obtained from https://www.nuget.org/packages/newtonsoft.json/

In the Code below the Root Object is the base class

 private static void Main(string[] args)
        {
            //Jsontochsharp.com
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://Your Json Source");
            request.Method = "GET"; request.Accept = "application/json;odata=verbose"; request.ContentType = "application/json;odata=verbose";
            WebResponse response = request.GetResponse(); string jSON = null; using (response)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    try
                    {
                        jSON = reader.ReadToEnd();
                    }
                    catch (Exception ex) { }
                }
            }

            // using javascript serializer
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            RootObject articleData = new RootObject();
            articleData = serializer.Deserialize<RootObject>(jSON);
        }
net core six article

ASP.NET CORE 6 JWT Authentication

Apollo11 in Tech
  ·   9 min read
>