Newtonsoft JSON Deserialize in C# with Example

Introduction

This article is about Newtonsoft JSON deserializing with a C# example. The Newtonsoft.JSON namespace provides classes that are used to implement the core services of the framework. It provides methods for converting between .NET types and JSON types.

Let’s follow the tutorial below to learn how to use newtonsoft.json with C#.

Step 1. Create a database in MySQL with the name “test” and create a table with the name “user”, as shown below.

Newtonsoft Json Deserialize C# Example

Step 2. Create a new application project. In Visual Studio, on the menu, click File> New > Project. For more details, see the following menu on the display.

Newtonsoft Json Deserialize C# Example

Step 3. Then the window 'New Project' will appear, which should look like the screenshot below.

Newtonsoft Json Deserialize C# Example

Step 4. Write down the name of the project that will be created in the field Name. Specify the directory storage project by accessing the field Location. Next, give the name of the solution in the Solution Name. Then click OK.

using System;
using System. collections.Generic;
using System.Linq;
using System.Text;
namespace consoleApplication1
{
      class Program
      {
          static void Main(string[]args)
           {
             }
         }
     }

Step 5. Create a new Windows form like the one shown below.

Newtonsoft Json Deserialize C# Example

Step 6. Create a new class, “module post,” for requesting json parse from the rest api client. Write the following program listing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
namespace newtonsoft_json
{
    public class modulePost
    {
        public static string urlServer = "http://localhost/json/ws.php";

        public void setURL(string url)
        {
            urlServer = url;
        }
        public string getURL()
        {
            return urlServer;
        }
        public string Post(string data)
        {
            string DataFromPHP = null;
            try
            {
                string url = getURL();
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
                WebReq.Timeout = 1900000;
                WebReq.Method = "POST";
                WebReq.ContentType = "application/x-www-form-urlencoded";
                WebReq.ContentLength = buffer.Length;
                Stream PostData = WebReq.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();
                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                DataFromPHP = _Answer.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return DataFromPHP;
        }
    }
}

Step 7Next, go back to the Windows form and view the code in order to write the following program listing.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
namespace newtonsoft_json
{
    public partial class Form1 : Form
    {
        modulePost _modul = new modulePost();
        public Form1()
        {
            InitializeComponent();
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string firstname, lastname, address;
            string app;
            string module;
            string action;
            string entity;
            string data;
            string respon;
            string json;
            try
            {
                app = "user";
                module = "user";
                action = "loginUser";
                entity = "&username=" + txtUsername.Text + "&password=" + txtPassword.Text;
                data = "&app=" + app + "&module=" + module + "&action=" + action + "" + entity;
                respon = _modul.Post(data);
                json = respon.TrimStart('[');
                json = json.TrimEnd(']');
                JObject o = JObject.Parse(json);
                JArray jsonarray = (JArray)o["data"];
                for (int i = 0; i < jsonarray.Count; i++)
                {
                    JObject aItem = (JObject)jsonarray[i];
                    firstname = (string)aItem["firstname"];
                    lastname = (string)aItem["lastname"];
                    address = (string)aItem["address"];

                    MessageBox.Show("Data Found My Name is " + firstname + " " + lastname + " and I Live at " + address);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred: " + ex.Message);
            }
        }
    }
}

Step 8. After you write down the program listings, press the F5 key to run the program. If you successfully connect your database, the result is.

Newtonsoft Json Deserialize C# Example

We have explained how to make a simple program with an example in C# using Visual Studio 2010 and MySQL. For those of you who want to download the source code of the program, you also can. Hopefully, this discussion is helpful to you.

You can see the Deserialize C# Example from the Github project Here.

Thank you for reading this article, I hope it was useful for you. 


Similar Articles