In this article you can find how to convert C# object into JSON using Json.NET (Newtonsoft.Json) library. It is available as a NuGet package for free, so you can easily install it from nuget.org repository.
Let’s create an example class which object will be converted into JSON.
1 2 3 4 5 6 7 8 |
public class Place { public string Name { get; set; } public string Country { get; set; } public string City { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } } |
Now we need to create an instance of Place object.
1 2 3 4 5 6 7 8 |
var centralPark = new Place() { Name = "Central Park", Country = "USA", City = "New York", Latitude = 40.785091, Longitude = -73.968285 }; |
Having the object we are ready to convert it to JSON string. We’ll use SerializeObject function from JsonConvert class.
1 |
var json = Newtonsoft.Json.JsonConvert.SerializeObject(centralPark); |
The type of json variable is string, so let’s print it to console.
1 |
Console.WriteLine(json); |
Result:
1 |
{"Name":"Central Park","Country":"USA","City":"New York","Latitude":40.785091,"Longitude":-73.968285} |
As we can see the JSON is not formatted and difficult to read. We can solve that issue by calling SerializeObject function passing two parameters where first is object to be serialized and second is formatting option. Choosing Indented we will receive nicely formatted JSON.
1 |
var formattedJson = Newtonsoft.Json.JsonConvert.SerializeObject(centralPark, Newtonsoft.Json.Formatting.Indented); |
Print to console.
1 |
Console.WriteLine(formattedJson); |
Result:
1 2 3 4 5 6 7 |
{ "Name": "Central Park", "Country": "USA", "City": "New York", "Latitude": 40.785091, "Longitude": -73.968285 } |