Introduction

JSON (JavaScript Object Notation) is a lightweight data interchange format commonly used in web applications for transmitting data between a server and a client. In C#, working with JSON is made easy with libraries like System.Text.Json and Newtonsoft.Json (Json.NET). This post will guide you through the basics of parsing, serializing, and deserializing JSON in C#.

Using System.Text.Json

System.Text.Json is a high-performance JSON library included in .NET Core 3.0 and later. It provides methods for parsing JSON into objects and serializing objects into JSON.

Parsing JSON

Parsing JSON involves converting JSON data into a C# object.

Example: Parsing JSON String into Object

using System;
using System.Text.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string jsonString = "{\"Name\":\"John\",\"Age\":30}";
            Person person = JsonSerializer.Deserialize<Person>(jsonString);
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonSerializer.Deserialize: Converts a JSON string into a C# object of type Person.
  • Person Class: Represents the structure of the JSON data.

Output:

Name: John, Age: 30

Serializing Objects

Serializing objects involves converting C# objects into JSON format.

Example: Serializing Object into JSON String

using System;
using System.Text.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Person person = new Person { Name = "John", Age = 30 };
            string jsonString = JsonSerializer.Serialize(person);
            Console.WriteLine(jsonString);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonSerializer.Serialize: Converts a C# object of type Person into a JSON string.

Output:

{"Name":"John","Age":30}

Using Newtonsoft.Json (Json.NET)

Newtonsoft.Json (Json.NET) is a popular third-party library for JSON handling in C#. It provides additional features and flexibility compared to System.Text.Json.

Installing Newtonsoft.Json

To use Newtonsoft.Json, you need to install the NuGet package.

  1. Install via NuGet Package Manager:
  • Right-click on your project in Visual Studio.
  • Select “Manage NuGet Packages”.
  • Search for Newtonsoft.Json and click “Install”.

Parsing JSON

Example: Parsing JSON String into Object with Newtonsoft.Json

using System;
using Newtonsoft.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string jsonString = "{\"Name\":\"John\",\"Age\":30}";
            Person person = JsonConvert.DeserializeObject<Person>(jsonString);
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonConvert.DeserializeObject: Converts a JSON string into a C# object of type Person using Newtonsoft.Json.

Output:

Name: John, Age: 30

Serializing Objects

Example: Serializing Object into JSON String with Newtonsoft.Json

using System;
using Newtonsoft.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Person person = new Person { Name = "John", Age = 30 };
            string jsonString = JsonConvert.SerializeObject(person);
            Console.WriteLine(jsonString);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonConvert.SerializeObject: Converts a C# object of type Person into a JSON string using Newtonsoft.Json.

Output:

{"Name":"John","Age":30}

Working with JSON Arrays

You can also work with JSON arrays to parse and serialize collections of objects.

Example: Parsing JSON Array into List of Objects

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string jsonString = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Jane\",\"Age\":25}]";
            List<Person> people = JsonConvert.DeserializeObject<List<Person>>(jsonString);
            foreach (var person in people)
            {
                Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
            }
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonConvert.DeserializeObject>: Converts a JSON array string into a list of Person objects.

Output:

Name: John, Age: 30
Name: Jane, Age: 25

Example: Serializing List of Objects into JSON Array

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            List<Person> people = new List<Person>
            {
                new Person { Name = "John", Age = 30 },
                new Person { Name = "Jane", Age = 25 }
            };
            string jsonString = JsonConvert.SerializeObject(people);
            Console.WriteLine(jsonString);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Explanation:

  • JsonConvert.SerializeObject: Converts a list of Person objects into a JSON array string.

Output:

[{"Name":"John","Age":30},{"Name":"Jane","Age":25}]

Full Example Code

Here is the complete example code demonstrating parsing, serializing, and deserializing JSON using both System.Text.Json and Newtonsoft.Json:

// Using System.Text.Json
using System;
using System.Text.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // System.Text.Json examples
            Console.WriteLine("System.Text.Json examples:");

            string jsonString = "{\"Name\":\"John\",\"Age\":30}";
            Person person = JsonSerializer.Deserialize<Person>(jsonString);
            Console.WriteLine($"Parsed Name: {person.Name}, Age: {person.Age}");

            string serializedString = JsonSerializer.Serialize(person);
            Console.WriteLine($"Serialized JSON: {serializedString}");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

// Using Newtonsoft.Json
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JsonExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Newtonsoft.Json examples
            Console.WriteLine("Newtonsoft.Json examples:");

            string jsonString = "{\"Name\":\"John\",\"Age\":30}";
            Person person = JsonConvert.DeserializeObject<Person>(jsonString);
            Console.WriteLine($"Parsed Name: {person.Name}, Age: {person.Age}");

            string serializedString = JsonConvert.SerializeObject(person);
            Console.WriteLine($"Serialized JSON: {serializedString}");

            // JSON Array example
            string jsonArrayString = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Jane\",\"Age\":25}]";
            List<Person> people = JsonConvert.DeserializeObject<List<Person>>(jsonArrayString);
            foreach (var p in people)
            {
                Console.WriteLine($"Name: {p.Name}, Age: {p.Age}");
            }

            string serializedArrayString = JsonConvert.SerializeObject(people);
            Console.WriteLine($"Serialized JSON Array: {serializedArrayString}");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Conclusion

Handling JSON in C# is straightforward with the help of libraries like System.Text.Json and Newtonsoft.Json. These libraries provide robust methods for parsing, serializing, and deserializing JSON data, making it easier to work with web APIs and other JSON-based data sources.

Similar Posts