Serialize Any .NET Object to a JSON String

Serialize Any .NET Object to a JSON String

The following steps explain how to serialize any .NET object into a JSON string. This tip uses the .NET 3.0 Framework. You’ll find this capability particularly helpful in applications that use AJAX to pass objects from the server to the client code.

Assume you have a Person object defined as shown below:

public class Person{  public int ID { get; set; }  public string FirstName { get; set; }  public string LastName { get; set; }}

Now assume you need to serialize this object to a JSON string to pass it to a client-side script. It turns out you can easily convert an instance of the Person class (or any .NET object) to a JSON string, by using an “extension method” (a capability released with .NET 3.0). To create a JSON serialization extension method, use the following code:

using System.Web.Script.Serialization;namespace JSON.Namespace{  public static class JSONHelper  {     public static string ToJSON(this object obj)     {        JavaScriptSerializer serializer = new JavaScriptSerializer();        return serializer.Serialize(obj);     }  }}

The JavaScriptSerializer class (in System.Web.Script.Serialization) handles the actual object-to-JSON conversion. Note that the ToJSON() extension method above is defined for type Object, which means you can use it with all .NET objects. This means that in addition to calling ToJSON() on a Person object, you could call it the same way on a collection of Person objects or any other .NET datatype. The following examples show how to use the ToJSON() method:

using JSON.Namespace; //Reference the namespace that contains ToJSON()Person person = new Person() {    ID=1, FirstName="Dev",    LastName="Jackson" }; //Create a Person object   //Convert to a JSON string    string JsonString = person.ToJSON();

The output of the preceding code would be:

[{"ID":1, "FirstName":"Dev", "LastName":"Jackson"}]

Conveniently, VS 2008 provides Intellisense and compile-time support for extension methods, just as if they were built-in methods.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as