December 26, 2023

Serialize with System.Text.Json.JsonSerializer

The System.Text.Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). When serializing C# objects to json, by default all public properties are serialized.

Lets say we have this User class object we want to serialize:

 class User
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string? Email { get; set; }
     public string Password { get; set; }
 }

var obj = new User
 {
     Id = 1,
     Name = "Idrees",
     Email = null,
     Password = "123"
 };

If we serialize this object:

string txtJson = Json.JsonSerializer.Serialize(obj);

We will get the this json:

{"Id":1,"Name":"Idrees","Email":null,"Password":"123"}

If we want to skip the Password property, we can use the attribute [JsonIgnore] on that property.

After this change the User class will look like this:

 class User
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string Email { get; set; }
     [JsonIgnore]
     public string Password { get; set; }
 }

Serializing now will give you this result:

{"Id":1,"Name":"Idrees","Email":null}

Notice that the Password property is no longer serialized.

You can also specify the condition for exclusion by setting the [JsonIgnore] attribute's Condition property.

In above example, we have set the null value for Email property and it is showing null in serialized json text.

To exclude that property we can specify the condition to ignore when it has null value. After this change the User class will become like this:

 class User
 {
     public int Id { get; set; }
     public string Name { get; set; }
     [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
     public string? Email { get; set; }
     [JsonIgnore]
     public string Password { get; set; }
 }

The serialization will remove the Email property and generate this json.

{"Id":1,"Name":"Idrees"}

References:

No comments:

Post a Comment