CSharp C# Convert Object To JSON

Kevin FOO
2 min readApr 6, 2021

--

Constructing JSON by concatenating string is not the best way as it will probably lead to bugs in your application. The easiest way to do it in CSharp(C#) is to use the library by Newtonsoft.

static void Main(string[] args)
{
var n = new Name();
n.FirstName = "William";
n.MiddleName = "Henry";
n.LastName = "Gates";
var c = new Contact();
c.Name = n;
c.PhoneNumber = "+1 425-882-8080";
Console.WriteLine(JsonConvert.SerializeObject(c));
}
private class Name {
[JsonProperty("first_name")]
public string FirstName;
[JsonProperty("middle_name")]
public string MiddleName;
[JsonProperty("last_name")]
public string LastName;
}
private class Contact {
[JsonProperty("name")]
public Name Name;
[JsonProperty("phone_number")]
public string PhoneNumber;
}

The code above will generate output as shown below.

The JsonProperty annotation is important if you want to generate JSON attribute different from the class variable. Neglecting the annotation will generate output like shown below.

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet