The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null
values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null
by default.
And, this would work fine for class fields if they are null
s. Look at this example:
public class Movie
{
public string Name { get; set; }
public string Description { get; set; }
public string Classification { get; set; }
public string Studio { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<string> ReleaseCountries { get; set; }
}
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys"
// }
In your case values for certain keys are null
s, but that's not the same as in the documentation provided.
This might help you, but you should be aware of how ToDictionary
affects performance:
var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
.ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);
dict
to not include null values then serialize?null
values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized tonull
by default.