Search code examples
c#jsonserialization

C#: How can I select json properties which will be written to file, and which will not?


For an example, we have this class:

public class Foo
{
    public string A { get; set; } = "Hello world! This is a good string!";
    public string B { get; set; } = "Hello world! This is a good string!";
    public string C { get; set; } = "Hello world! This is a good string!";
}

Later, somewhere in code, we do this:

var foo1 = new Foo { A = "Test" };
File.WriteAllText("C:\some\path\file1.json", JsonConvert.SerializeObject(foo1));

var foo2 = new Foo { B = "Test" };
File.WriteAllText("C:\some\path\file2.json", JsonConvert.SerializeObject(foo2));

Both files will have the same "not used, default" properties:

file1.json:

{
    "A": "Test",
    "B": "Hello world! This is a good string!",
    "C": "Hello world! This is a good string!"
}

file2.json:

{
    "A": "Hello world! This is a good string!",
    "B": "Test",
    "C": "Hello world! This is a good string!"
}

The question is - how can i get rid of unused properties to save my disk space? I dont need them, because their default value is assigned in initialization code. May be i can somehow select which properties i need to serialize and which not? Is there any easier way than to dynamically add and remove [JsonIgnore] attribute to the class?


Solution

  • You should set DefaultValueHandling = DefaultValueHandling.Ignore of JsonSerializerSettings.

    This doesn't serialize properties with default values.

    Like this :

    var foo1 = new Foo { A = "Test" };
    File.WriteAllText(@"C:\some\path\file1.json", JsonConvert.SerializeObject(foo1, new JsonSerializerSettings
    {
        DefaultValueHandling = DefaultValueHandling.Ignore
    }));
    

    Same for the second file.