When you create any application using OOP, you create your own custom objects, classes, etc. In the same framework that custom object is readable, so every client (and/or server) application will understand its structure. Let’s say there’s a server-client application that stores data in custom class then save it to disk. Both app is written in .NET framework using C#, so both can understand that custom object (see and understand its properties, methods, etc) and both know the File class in System.IO namespace to read and write the files.
But what if you want to pass an object to a very differnt and unknow environment? Or to a simple browser that only understand text.. How do you know there’s also .NET framework? You don’t know. But you have to send your object. Here comes the JSON (son of Java, LOL). JSON is a lightweight data-interchange format that is easy to read and write by both humans and computers. JSON is a text format and absolutely language independent.
JSON is a collection (array) of key-value pairs. In various languages (C, C++, C#, Java, Perl, Python, JavaScript, etc.) this is serialized as an object, struct, class, record, dictionary, hash table, keyed list, associative array, array, vector, list or sequence.
An object (unordered set of key-value pairs) always starts with left brace ({) and ends with right brace (}), the name is followed by colon (:) and the key-value pairs are separated by comma (,).
An array (ordered collection of values) always starts with left bracket ([) and ends with right bracket (]). Values are separated by comma (,).
A value can be string in double quotes (“), or number, or boolean, or null, or an object or even an array. As you can think, these structures can be nested of course.
Strings and numbers are very similar to C or Java string/number, except that octal and hexa formats are not used.
To create JSON from any object (serialize) or get back your object from JSON (deserialize) can be done using NewtonSoft’s Json library.
First let me show you a simple example to create a JSON string. Let’s create 3+1 classes. The plus 1 class is use to be to store the whole list of objects stored in JSON. That’s why its name contains the word RootObject.
public class RentalCompany { public Guid Id { get; set; } public string Name { get; set; } public Address MainOfficeAddress { get; set; } public IList Branches { get; set; } } public class Branch { public Guid Id { get; set; } public string Name { get; set; } public Address BranchAddress { get; set; } } public class Address { public Guid Id { get; set; } public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } public string Country { get; set; } }
and the RootObject class:
public class RentalCompanyRootObject { public IList RentalCompany { get; set; } }
As you can see I created classes to get some nesting in our JSON (custom type properties). Some people like to decorate the properties with JsonProperty tag, so the JSON result will have those names that are in JSON properties:
public class RentalCompany { public Guid Id { get; set; } public string Name { get; set; } [JsonProperty("Address")] public Address MainOfficeAddress { get; set; } [JsonProperty("Branch")] public IList Branches { get; set; } } public class Branch { public Guid Id { get; set; } public string Name { get; set; } [JsonProperty("Address")] public Address BranchAddress { get; set; } } public class RentalCompanyRootObject { [JsonProperty("MyRentalCompanies")] public IList RentalCompany { get; set; } }
To see the result, create a simple console application and fill up our rental company list and store all the data in class level variables:
private static readonly RentalCompanyRootObject RootObject = new RentalCompanyRootObject(); private static readonly IList Companies = new List(); private static string _jsonResult;
The filling method:
private static void CreateCompany() { IList branches = new List(); branches.Add(new Branch { Id = Guid.NewGuid(), Name = "Branch 1", BranchAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 1.", City = "City 1", Country = "Country 1", ZipCode = "ZIP001" } }); branches.Add(new Branch { Id = Guid.NewGuid(), Name = "Branch 2", BranchAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 2.", City = "City 2", Country = "Country 2", ZipCode = "ZIP002" } }); branches.Add(new Branch { Id = Guid.NewGuid(), Name = "Branch 3", BranchAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 3.", City = "City 3", Country = "Country 3", ZipCode = "ZIP003" } }); branches.Add(new Branch { Id = Guid.NewGuid(), Name = "Branch 4", BranchAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 4.", City = "City 4", Country = "Country 4", ZipCode = "ZIP004" } }); Companies.Add(new RentalCompany { Id = Guid.NewGuid(), Name = "Company 1", MainOfficeAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 33.", City = "City 33", Country = "Country 33", ZipCode = "ZIP033" }, Branches = branches }); Companies.Add(new RentalCompany { Id = Guid.NewGuid(), Name = "Company 2", MainOfficeAddress = new Address { Id = Guid.NewGuid(), Street = "Street name 44.", City = "City 44", Country = "Country 44", ZipCode = "ZIP044" }, Branches = branches }); }
Because of the nesting, first we create the branch offices then we add them to the companies.
The main method is simple:
private static void Main(string[] args) { CreateCompany(); RootObject.RentalCompany = Companies; _jsonResult = JsonConvert.SerializeObject(RootObject); Console.WriteLine(_jsonResult); Console.ReadKey(); }
The result in the console will be this:
I like to check every JSON in Notepad++. It’s a great text editor with many plugins, like JSON viewer. If you copy the console result to Notepad++, you should see something like this:
Turn on JSON viewer and formatter from the JSON menu:
And you’ll get this result:
The nesting is clearly visible. You may also recognize that I used objects and not arrays, that’s why there’s Object written on the left panel and the JSON starts with ‘{‘ and not with ‘[‘.