Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

476
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda