0

I have a class that I referenced from an internal nuget package

public class Person
{
     public string Name { get; set;}
     public int Age{ get; set;}
}

and I am using System.Text.Json to serialize the instantiated message.

When I initialized an instance of the class, say for example

Person p = new Person() {Name = "Abraham"};

and serialized it, the resulting string still includes the Age property.

Person {
     "Name": "Abraham",
     "Age": 0
}

May I know how will I be able to serialize an instance of a class with only the initialized properties included.

dbc
  • 104,963
  • 20
  • 228
  • 340
Joseph
  • 502
  • 4
  • 15
  • 2
    `Age` *is* "initialized" though... to its default value. Did you want to use `int?` instead? – David Oct 18 '22 at 17:04
  • no, as I have said in the first line, the class is from an internal nuget package to which I have no control to change the type to a nullable. – Joseph Oct 18 '22 at 17:10
  • 1
    You could potentially write a custom JSON serializer which ignores `int` properties with the value `0`. Or perhaps write your own class(es) and transpose to that before serializing. – David Oct 18 '22 at 17:11
  • Writing my own classes is an option but I have a requirement to use that class from the package. – Joseph Oct 18 '22 at 17:12

1 Answers1

1

you can use JsonIgnoreCondition option

string json = System.Text.Json.JsonSerializer
.Serialize(p, new JsonSerializerOptions {WriteIndented=true, DefaultIgnoreCondition = 
System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault});

or as a property attribute

public class Person
{
    public string Name { get; set; }
    [System.Text.Json.Serialization.JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public int Age { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
  • I have thought aboyut the use of JsonIgnoreCndition.WhenWritingDefault, although there are numerical properties that I need to release in the data even though their value is 0, and there are some that I really don't need to. Using that will remove those properties. – Joseph Oct 18 '22 at 19:54
  • I know what I need. Clearly stated above. – Joseph Oct 18 '22 at 20:43