How to process JSON using C# and Newtonsoft.Json?
In this post, I’ll tell you how to process JSON using C# and Newtonsoft.Json with proper code. Newtonsoft.Json is a popular high-performance JSON framework for .NET and is also know by Json.NET.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
– http://www.json.org/
I’ve created a console application in Visual Studio 2015 so that it is easy to simply write my program and see the output in console quickly. In order to process JSON using C#, the next step is to install Newtonsoft.Json framework using Nuget package manager to this project.
Following are the ways to use Newtonsoft.Json framework to serialize and deserialize JSON easily:
- JsonSerializer is the quickest method of converting between JSON text and a .NET object. It converts .NET objects into their JSON equivalent and back again by mapping the .NET object property names to the JSON property names and copies the values.
- JsonConvert is useful for simple cases where you want to convert to and from a JSON string. This provides the
SerializeObject()andDeserializeObject()methods onJsonConvertprovide an easy-to-use wrapper overJsonSerializer.
I’ve also created a class named `Author` as shown below that will be used for the type of object for deserialization.
public class Author
{
public string Name { get; set; }
public List<string> Courses { get; set; }
public DateTimeOffset Since { get; set; }
public bool IsHappy { get; set; }
public string Country { get; set; }
public int Age { get; set; }
public List<Author> FavouriteAuthors { get; set; }
}
To run the application and see the result in console, I’ve following in the `Program.cs` file:
class Program
{
static void Main(string[] args)
{
Console.Clear();
JsonConvertDemo.ShowDemo();
Console.ReadLine();
}
}
Next, I’ve created another class named `JsonConvertDemo` that has only one method named `ShowDemo` as shown below:
public class JsonConvertDemo
{
private static string authorRawData = @"{
'Name': 'Sid',
'Courses': [
'Course 1',
'Course 2'
],
'Since': '2017-03-01T22:09:39.9369001+00:00',
'IsHappy': true,
'Country': 'India',
'Age': 25
}";
public static void ShowDemo()
{
Console.WriteLine("Follow is the JSON raw data:");
Console.WriteLine(authorRawData);
var author = JsonConvert.DeserializeObject<Author>(authorRawData);
Console.WriteLine(Environment.NewLine + author.Name + " is an author from " + author.Country);
string serializedAuthorData = JsonConvert.SerializeObject(author);
Console.WriteLine(Environment.NewLine + serializedAuthorData);
string formattedSerializedAuthorData = JsonConvert.SerializeObject(author, Formatting.Indented);
Console.WriteLine(Environment.NewLine + formattedSerializedAuthorData);
}
}
- Line no. 19 writes the JSON author data that is defined in a private variable named `authorRawData` on line no. 4.
- On line no. 21, we use the `DeserializeObject` method to convert the string to a .NET object. Notice the `<Author>` type that is passed to the method which is the type of the object to deserialize to. And line no. 22 writes the name and country of author.
- Line no. 24 uses the `SerializeObject` method to convert the `author` object back to string format and in the next line it is added to the console. The output in the console is not formatted in the way you would expect.
- Line no. 27 also serialize the object but uses one of the overload of `SerlializeObject` by passing `Formatting.Indented` as the formatting option for the underlying `Newtonsoft.Json.JsonTextWriter`. And when this new object is written to the console, the output is now formatted properly.
I hope this is useful to understand how to process JSON using C# and Newtonsoft.Json. I’ll be writing more posts about this popular high-performance JSON framework soon. If you would like to get updates, please subscribe to my blog.
