Json.NET by Newtonsoft is the de-facto standard when it comes to work with JSON in .Net. The library is very popular, offers great flexibility and is easy to use. Let’s look on what you have to do to serialize and deserialize objects to JSON.
Installation
Open the Package Management window in Visual Studio and search for the Newtonsoft.Json NuGet package to add it to your project:
Or install it with this command in the Package Manager Console:
1 |
PM> Install-Package Newtonsoft.Json |
All your questions should be answered in the well-written official documentation, that includes more than 100 examples on how to use Json.NET.
Serialize and deserialize objects to and from JSON
For my examples I use these the class BlogPost and an enum called State to show how you can serialize those often-used combinations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class BlogPost { public int Id { get; set; } public string Title { get; set; } public DateTime? PublishedAt { get; set; } public State State { get; set; } public List<string> Tags { get; set; } public BlogPost() { Tags = new List<string>(); } } public enum State { Draft = 1, Published = 2, Deleted = 3 } |
All you need to serialize your objects to JSON is to call JsonConvert.SerializeObject
:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var post = new BlogPost { Id = 1, State = State.Published, PublishedAt = DateTime.Now, Title = "How to use JSON.net" }; post.Tags.Add("C#"); post.Tags.Add("JSON"); string output = JsonConvert.SerializeObject( post, Formatting.Indented); |
The Formatting.Indented
flag is optional. It will intent your JSON and makes it more readable:
1 2 3 4 5 6 7 8 9 10 |
{ "Id": 1, "Title": "How to use JSON.net", "PublishedAt": "2019-04-01T21:29:34.1258843+02:00", "State": 2, "Tags": [ "C#", "JSON" ] } |
Turning JSON back into an object is even simpler. All it takes is a call to JsonConvert.DeserializeObject
, a type you want to serialize it back to and your JSON string:
1 |
var dPost= JsonConvert.DeserializeObject<BlogPost>(output); |
Serialize and deserialize lists of objects to and from JSON
Serializing a list of objects is no different than using a single object:
1 2 3 4 5 6 7 8 |
var listOfPosts = new List<BlogPost>(); listOfPosts.Add(post); listOfPosts.Add(post2); listOfPosts.Add(post3); var jsonList = JsonConvert.SerializeObject( listOfPosts, Formatting.Indented); |
This results in a JSON array with three posts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
[ { "Id": 1, "Title": "How to use JSON.net", "PublishedAt": "2019-04-01T21:29:34.1258843+02:00", "State": 2, "Tags": [ "C#", "JSON" ] }, { "Id": 2, "Title": "More use cases for JSON.net", "PublishedAt": null, "State": 1, "Tags": [] }, { "Id": 3, "Title": "How to use ....", "PublishedAt": "2018-10-01T21:31:39.9366028+02:00", "State": 3, "Tags": [] } ] |
Turning that JSON back to a list of objects uses a slightly different command. This time you want a list of BlogPosts what you need to say explicitly in the type:
1 |
var dList = JsonConvert.DeserializeObject<List<BlogPost>>(jsonList); |
If you do not specify the list and instead use BlogPost, you will get this error:
1 2 |
// does not work with a list var error = JsonConvert.DeserializeObject<BlogPost>(jsonList); |
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type ‘JsonExamples.BlogPost’ because the type requires a JSON object (e.g. {“name”:”value”}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {“name”:”value”}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like Listthat can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
If you read the error message you see another great point in Json.NET – it helps you to do use its API the right way with useful error messages.
Influence the serialization
The default serialization includes NULL values and writes the property names exactly as you wrote them in your class:
1 |
var defaultSerialization = JsonConvert.SerializeObject(post2); |
1 |
{"Id":2,"Title":"More use cases for JSON.net","PublishedAt":null,"State":1,"Tags":[]} |
Especially when you exchange JSON with other systems, then you may need a different serialization approach. You can change all the behaviour using a JsonSerializerSettings
object that you can pass into the SerializeObject
method. To use camelCase for property names, the MicrosoftDateFormat
and ignores Null values you can use these settings:
1 2 3 4 5 6 7 8 |
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore, DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }; var postCamelCase = JsonConvert.SerializeObject(post3, settings); |
1 |
{"id":3,"title":"How to use ....","publishedAt":"\/Date(1538422299936+0200)\/","state":3,"tags":[]} |
Influence the serialization even more
Sometimes you need to have even more control on how properties are serialized to JSON. In this case you can use JsonPropertyAttribute
to use a different name or JsonConverter
to use a different strategy to serialize Enum values. You put this kind of attributes on your business class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Comment { public Guid Id { get; set; } [JsonPropertyAttribute("User")] public string FullName { get; set; } public string Text { get; set; } [JsonConverter(typeof(StringEnumConverter))] public State State { get; set; } public Comment() { Id = Guid.NewGuid(); } } |
If you now serialize your object you don’t need to add a settings object. The object itself has all information on its serialization inside and Json.NET will use it accordingly:
1 2 3 4 5 6 7 8 9 |
var comment = new Comment { FullName = "JSON Demo", State = State.Published, Text = "Hello world!" }; var jsonFromProperties = JsonConvert.SerializeObject( comment, Formatting.Indented); |
1 2 3 4 5 6 |
{ "Id": "58deb4b9-f3e5-408e-938f-c6a03dc860e0", "User": "JSON Demo", "Text": "Hello world!", "State": "Published" } |
Ignoring properties
If you have some properties or fields you do not want to serialize, you can use the annotation [JsonIgnore]
to supress them:
1 2 |
[JsonIgnore] public string Text { get; set; } |
Add this annotation to the Text
property of the Comment
class from above and the field is no longer present in the JSON file:
1 2 3 4 5 |
{ "Id": "ac825b9a-b522-484d-8bdb-1e493d3e8b73", "User": "JSON Demo", "State": "Published" } |
Conclusion
Working with JSON in .Net is a super simple task thanks to Json.NET from Newtonsoft. All you need to know is how to serialize and deserialize objects and lists and you can solve all tasks involving JSON. Should something special occur you most like find the specific command in their great documentation.