In this article I will explain with an example, how to read (parse) JSON data from JSON file in Windows Forms Application using C# and VB.Net.
The JSON file will be read from disk Folder (Directory) using JavaScriptSerializer class in Windows Forms Application using C# and VB.Net.
The JSON string
Following is the JSON string saved inside a JSON file in the disk Folder (Directory).
[
{
"CustomerId":1,
"Name":"John Hammond",
"Country":"United States"
},
{
"CustomerId":2,
"Name":"Mudassar Khan",
"Country":"India"
},
{
"CustomerId":3,
"Name":"Suzanne Mathews",
"Country":"France"
},
{
"CustomerId":4,
"Name":"Robert Schidner",
"Country":"Russia"
}
]
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Web.Script.Serialization;
VB.Net
Imports System.IO
Imports System.Web.Script.Serialization
Read (Parse) JSON string from File using C# and VB.Net
Inside the Form Load event, the contents of the JSON file are read using StreamReader class object from the disk Folder (Directory).
Then, an object of JavaScriptSerializer class is created and finally, the JSON string is read from StreamReader using the ReadToEnd method and is converted dynamic object using DeserializeObject method of JavaScriptSerializer class.
C#
private void Form1_Load(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(@"E:\Customers.json"))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var customers = serializer.DeserializeObject(reader.ReadToEnd());
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using reader As StreamReader = New StreamReader("E:\Customers.json")
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
Dim customers = serializer.DeserializeObject(reader.ReadToEnd())
EndUsing
EndSub
Screenshot
Downloads