Useful Extension Method 4: ToJson

Selim YILDIZ
1 min readJan 23, 2023

--

Here is the fourth extension method of the series called “10 useful extension methods in C#”.

This is probably the most common extension method :)

Here is the extension:

public static string ToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
}

Note that the extension method uses the JsonConvert.SerializeObject method from the Newtonsoft.Json library to perform the serialization, passing the object as a parameter.

This is the usage:

Person person = new Person { Name = "Selim YILDIZ", Age = 31 };

string json = person.ToJson();

Console.WriteLine(json);

// Output: {"Name":"Selim YILDIZ","Age":31}

This extension method works for any object, as it takes an object of type object as parameter, so it can be applied to any object and can be used to serialize any class or struct and it will work as long as the object you are trying to serialize can be serialized by Newtonsoft Json.

In conclusion, the ToJson method is a useful utility method that allows developers to easily convert their classes and structs to JSON strings without having to manually write the serialization code. This can be particularly useful when working with web applications and services, as JSON is a commonly used format for exchanging data over the internet.

This method can greatly simplify the process of working with JSON, and is a valuable addition to any developer’s toolbox.

Thanks for reading!

--

--