Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

475
Views
System.Json - custom rules for property serialization skipping

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"
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!