Click or drag to resize
Json.NETReducing Serialized JSON Size
 

One of the common problems encountered when serializing .NET objects to JSON is that the JSON ends up containing a lot of unwanted properties and values. This can be especially significant when returning JSON to the client. More JSON means more bandwidth and a slower website.

To solve the issue of unwanted JSON, Json.NET has a range of built-in options to fine-tune what gets written from a serialized object.

JsonIgnoreAttribute and DataMemberAttribute

By default Json.NET will include all of a class's public properties and fields in the JSON it creates. Adding the JsonIgnoreAttribute to a property tells the serializer to always skip writing it to the JSON result.

Opt-out Serialization Example
 1public class Car
 2{
 3    // included in JSON
 4    public string Model { get; set; }
 5    public DateTime Year { get; set; }
 6    public List<string> Features { get; set; }
 7
 8    // ignored
 9    [JsonIgnore]
10    public DateTime LastModified { get; set; }
11}

If a class has many properties and you only want to serialize a small subset of them, then adding JsonIgnore to all the others will be tedious and error prone. The way to tackle this scenario is to add the DataContractAttribute to the class and DataMemberAttribute to the properties to serialize. This is opt-in serialization - only the properties you mark up will be serialized, unlike opt-out serialization using JsonIgnoreAttribute.

Opt-in Serialization Example
 1[DataContract]
 2public class Computer
 3{
 4    // included in JSON
 5    [DataMember]
 6    public string Name { get; set; }
 7
 8    [DataMember]
 9    public decimal SalePrice { get; set; }
10
11    // ignored
12    public string Manufacture { get; set; }
13    public int StockCount { get; set; }
14    public decimal WholeSalePrice { get; set; }
15    public DateTime NextShipmentDate { get; set; }
16}
Formatting

JSON written by the serializer with an option of Formatting set to Indented produces nicely formatted, easy-to-read JSON that is great for readability when you are developing. Formatting.None on the other hand keeps the JSON result small, skipping all unnecessary spaces and line breaks to produce the most compact and efficient JSON possible.

NullValueHandling

NullValueHandling is an option on the JsonSerializer and controls how the serializer handles properties with a null value. By setting a value of NullValueHandling.Ignore the JsonSerializer skips writing any properties that have a value of null.

NullValueHandling Class
1public class Movie
2{
3    public string Name { get; set; }
4    public string Description { get; set; }
5    public string Classification { get; set; }
6    public string Studio { get; set; }
7    public DateTime? ReleaseDate { get; set; }
8    public List<string> ReleaseCountries { get; set; }
9}
NullValueHandling Ignore Example
 1Movie movie = new Movie();
 2movie.Name = "Bad Boys III";
 3movie.Description = "It's no Bad Boys";
 4
 5string included = JsonConvert.SerializeObject(movie,
 6    Formatting.Indented,
 7    new JsonSerializerSettings { });
 8
 9// {
10//   "Name": "Bad Boys III",
11//   "Description": "It's no Bad Boys",
12//   "Classification": null,
13//   "Studio": null,
14//   "ReleaseDate": null,
15//   "ReleaseCountries": null
16// }
17
18string ignored = JsonConvert.SerializeObject(movie,
19    Formatting.Indented,
20    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
21
22// {
23//   "Name": "Bad Boys III",
24//   "Description": "It's no Bad Boys"
25// }

NullValueHandling can also be customized on individual properties using the JsonPropertyAttribute. The JsonPropertyAttribute value of NullValueHandling will override the setting on the JsonSerializer for that property.

DefaultValueHandling

DefaultValueHandling is an option on the JsonSerializer and controls how the serializer handles properties with a default value. Setting a value of DefaultValueHandling.Ignore will make the JsonSerializer skip writing any properties that have a default value to the JSON result. For object references this will be null. For value types like int and DateTime the serializer will skip the default uninitialized value for that value type.

Json.NET also allows you to customize what the default value of an individual property is using the DefaultValueAttribute. For example, if a string property called Department always returns an empty string in its default state and you don't want that empty string in your JSON, then placing the DefaultValueAttribute on Department with that value will mean Department is no longer written to JSON unless it has a value.

DefaultValueHandling Class
 1public class Invoice
 2{
 3    public string Company { get; set; }
 4    public decimal Amount { get; set; }
 5
 6    // false is default value of bool
 7    public bool Paid { get; set; }
 8    // null is default value of nullable
 9    public DateTime? PaidDate { get; set; }
10
11    // customize default values
12    [DefaultValue(30)]
13    public int FollowUpDays { get; set; }
14
15    [DefaultValue("")]
16    public string FollowUpEmailAddress { get; set; }
17}
DefaultValueHandling Ignore Example
 1Invoice invoice = new Invoice
 2{
 3    Company = "Acme Ltd.",
 4    Amount = 50.0m,
 5    Paid = false,
 6    FollowUpDays = 30,
 7    FollowUpEmailAddress = string.Empty,
 8    PaidDate = null
 9};
10
11string included = JsonConvert.SerializeObject(invoice,
12    Formatting.Indented,
13    new JsonSerializerSettings { });
14
15// {
16//   "Company": "Acme Ltd.",
17//   "Amount": 50.0,
18//   "Paid": false,
19//   "PaidDate": null,
20//   "FollowUpDays": 30,
21//   "FollowUpEmailAddress": ""
22// }
23
24string ignored = JsonConvert.SerializeObject(invoice,
25    Formatting.Indented,
26    new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
27
28// {
29//   "Company": "Acme Ltd.",
30//   "Amount": 50.0
31// }

DefaultValueHandling can also be customized on individual properties using the JsonPropertyAttribute. The JsonPropertyAttribute value of DefaultValueHandling will override the setting on the JsonSerializer for that property.

IContractResolver

For more flexibility, the IContractResolver provides an interface to customize almost every aspect of how a .NET object gets serialized to JSON, including changing serialization behavior at runtime.

IContractResolver Class
 1public class DynamicContractResolver : DefaultContractResolver
 2{
 3    private readonly char _startingWithChar;
 4
 5    public DynamicContractResolver(char startingWithChar)
 6    {
 7        _startingWithChar = startingWithChar;
 8    }
 9
10    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
11    {
12        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
13
14        // only serializer properties that start with the specified character
15        properties =
16            properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
17
18        return properties;
19    }
20}
21
22public class Book
23{
24    public string BookName { get; set; }
25    public decimal BookPrice { get; set; }
26    public string AuthorName { get; set; }
27    public int AuthorAge { get; set; }
28    public string AuthorCountry { get; set; }
29}
IContractResolver Example
 1Book book = new Book
 2{
 3    BookName = "The Gathering Storm",
 4    BookPrice = 16.19m,
 5    AuthorName = "Brandon Sanderson",
 6    AuthorAge = 34,
 7    AuthorCountry = "United States of America"
 8};
 9
10string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
11    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
12
13// {
14//   "AuthorName": "Brandon Sanderson",
15//   "AuthorAge": 34,
16//   "AuthorCountry": "United States of America"
17// }
18
19string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
20    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
21
22// {
23//   "BookName": "The Gathering Storm",
24//   "BookPrice": 16.19
25// }
See Also