1
votes

I am trying to migrate from Newtonsoft.Json to System.Text.Json However, I ran into a problem since I was using DefaultContractResolver. My "custom" behaviour have these rules for property serialization:

  1. Skip property serialization if it is marked with ReadOnly attribute
  2. Skip property serialization in case of null (this is supported)
  3. Skip property serialization which would serialize into an empty object

Example:

class Car
{
  [ReadOnly]
  public string Id { get; set; }

  public string Name { get; set; }

  public Person Owner { get; set; }
}

class Person
{
  [ReadOnly]
  public string Id { get; set; }

  public string Name { get; set; }
}

Now, imagine, we have this data if no rules would apply.

{
   "Id":"1234",
   "Name":"Skoda",
   "Owner":{
      "Id":"abcd",
      "Name":null
   }
}

Now, if I serialize the object, I would like to get this instead.

{
   "Name":"Skoda"
}
1
Welcome to StackOverflow! Just out of curiosity how did you solve this with Json.Net? - Peter Csala
BTW in case of System.Text.Json you have the following settings JsonSerializerOptions.IgnoreReadOnlyProperties and JsonSerializerOptions.IgnoreNullValues - Peter Csala

1 Answers

0
votes

In order to ignore individual properties, you need to use the [JsonIgnore] attribute along with one of these conditions:

  • Always;
  • Never;
  • WhenWritingDefault;
  • WhenWritingNull.

You can also define a default ignore condition through the JsonSerializerOptions type.

If additional behavior is needed, you should write a custom converter.

Example:

class Person
{
  [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
  public string Id { get; set; }

  [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  public string Name { get; set; }
}

More information:

How to ignore properties with System.Text.Json

How to write custom converters for JSON serialization (marshalling) in .NET