serialize class to json in csharp

To serialize a class to JSON in C#, we can use the Newtonsoft.Json NuGet package.

Here's an example:

main.cs
using Newtonsoft.Json;

// define a class to serialize
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// create an instance of the class
var person = new Person { Name = "John Doe", Age = 30 };

// serialize the class to JSON
string json = JsonConvert.SerializeObject(person);
325 chars
15 lines

In this example, we define a Person class with two properties (Name and Age), and create an instance of the class with some sample data. We then use the JsonConvert.SerializeObject method from the Newtonsoft.Json package to serialize the class to JSON, and store the resulting JSON string in a variable named json.

gistlibby LogSnag