In this article, I will show you how to convert a C# object into a JSON string. First of all, you must know what JSON is.
- JSON - JavaScript Object Notation.
- JSON is a syntax for storing and exchanging the data.
You may have come across many scenarios where you need JSON format of an object. Mainly it is used in API calls for exchanging the data from API to different web applications or between browser and server. Here, I will show a simple JSON converter capable to convert most of the C# object types into JSON without using any third party and .NET serializer library. I have written converter code in a class library and then consuming this library on a test project for testing.
Notes - You must know proper JSON syntax to understand the code.
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
I have kept JSON Converter class under namespace JsonPluto. Make sure to import correct namespace while testing. Serialize() method in JsonConvert class converts the C# object into a JSON string.
- Pass the object as a parameter in Serialize method.
- Create a solution and add a class library project and a test project into your solution.
Step 1
Below is the class JsonConverter which will parse this object into JSON.
Step 2
For testing, we will write a sample models class using all types of data type like int, string, double, bool, List, Dictionary, Object etc. to create the object instance. I have created a model class named "Company" to store the company information.
- using System;
- using System.Collections.Generic;
-
- namespace JsonConverterTest.Models
- {
- public class Comapany
- {
- public string Name { get; set; }
- public double TotalAsset { get; set; }
- public int TotalEmployee { get; set; }
- public bool IsGovtOrganisation { get; set; }
- public DateTime Established { get; set; }
- public List<Branch> Branches { get; set; }
- public Dictionary<string,Department> Departments { get; set; }
- public Management Management { get; set; }
-
- }
-
- public class Branch
- {
- public string Country { get; set; }
- public string State { get; set; }
- public Location Address { get; set; }
-
- }
-
- public class Location
- {
- public string BuildingName { get; set; }
- public string Street { get; set; }
- public int ZipCode { get; set; }
- }
-
- public class Department
- {
- public int DeptId { get; set; }
- public string DeptName { get; set; }
- }
-
- public class Management
- {
- public string CEO { get; set; }
- public string Founder { get; set; }
- }
- }
Step 3
Add a test project to your solution and now in test method, create a "Company" class instance and parse into JSON string.
- using System;
- using System.Collections.Generic;
- using JsonConverterTest.Models;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using JsonPluto;
-
- namespace JsonConverterTest
- {
- [TestClass]
- public class UnitTest1
- {
-
-
-
-
- private Comapany GetCompanyObject()
- {
- return new Comapany
- {
- Name = "CSG Solutions India Pvt Ltd",
- TotalEmployee = 50,
- Established = DateTime.Now,
- IsGovtOrganisation = false,
- TotalAsset = 20000000,
- Branches = new List<Branch>
- {
- new Branch
- {
- Country = "India",
- State = "Karnataka",
- Address = new Location
- {
- BuildingName = "Sri Hari Tower",
- Street = "2nd Main Road",
- ZipCode = 560016
- }
- },
- new Branch
- {
- Country = "USA",
- State = "Germantown",
- Address = new Location
- {
- BuildingName = "Zinc Tower",
- Street = "Germantown Road",
- ZipCode = 50001
- }
- }
- },
- Departments = new Dictionary<string, Department>
- {
- { "Engineering", new Department { DeptId = 001, DeptName = "Super Engineers" } },
- { "Support", new Department { DeptId = 002, DeptName = "24*7 Tech Support" } },
- { "Marketings", new Department { DeptId = 003, DeptName = "Tech Mavens" } }
- },
- Management = new Management { CEO = "Tarun Kumar Rajak", Founder = "Ashok Kisku" }
- };
- }
-
-
-
-
- [TestMethod]
- public void TestMethod1()
- {
- var json = JsonConverter.Serialize(GetCompanyObject());
- System.IO.File.WriteAllText(@"C:\Users\Public\Documents\Company.json", json);
- }
- }
- }
Step 4
Now, run the test method. For that, right-click the test method and click on "Run Test" or "Debug Test" option. Check the output file saved in path C:\Users\Public\Documents\Company.json.
The output file will be like below.
- {
- "Name": "CSG Solutions India Pvt Ltd",
- "TotalAsset": 20000000,
- "TotalEmployee": 50,
- "IsGovtOrganisation": false,
- "Established": "29-03-2018 21:52:37",
- "Branches": [
- {
- "Country": "India",
- "State": "Karnataka",
- "Address": {
- "BuildingName": "Sri Hari Tower",
- "Street": "2nd Main Road",
- "ZipCode": 560016
- }
- },
- {
- "Country": "USA",
- "State": "Germantown",
- "Address": {
- "BuildingName": "Zinc Tower",
- "Street": "Germantown Road",
- "ZipCode": 50001
- }
- }
- ],
- "Departments": {
- "Engineering": {
- "DeptId": 1,
- "DeptName": "Super Engineers"
- },
- "Support": {
- "DeptId": 2,
- "DeptName": "24*7 Tech Support"
- },
- "Marketings": {
- "DeptId": 3,
- "DeptName": "Tech Mavens"
- }
- },
- "Management": {
- "CEO": "Tarun Kumar Rajak",
- "Founder": "Ashok Kisku"
- }
- }
In the next article, I will demonstrate how to deserailize JSON back to C# object type. Please share your valuable feedback.