Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Net Core 3.1 System.Text.Json Ignore empty collection in serialization

Using Newtonsoft we had a custom resolver for ignoring empty collections. Is there any equivalent configuration for the new system.text.json in .Net core 3.1

like image 406
Leela Krishna Devalla Avatar asked Jan 13 '20 16:01

Leela Krishna Devalla


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

Conditionally ignore a property from .NET5's official How to migrate from Newtonsoft.Json to System.Text.Json from 2020 Dec 14 states:

System.Text.Json provides the following ways to ignore properties or fields while serializing:

  • The [JsonIgnore] attribute (...).
  • The IgnoreReadOnlyProperties global option (...).
  • (...) JsonSerializerOptions.IgnoreReadOnlyFields global (...)
  • The DefaultIgnoreCondition global option lets you ignore all value type properties that have default values, or ignore all reference type properties that have null values.

These options don't let you:

  • Ignore selected properties based on arbitrary criteria evaluated at run time.

For that functionality, you can write a custom converter. Here's a sample POCO and a custom converter for it that illustrates this approach:

(An example of a custom converter for a type follows)

Please note that this converter needs to be a converter for the type that contains the property that is a collection, it's not a converter for the collection type (for that see my 2nd answer).

like image 148
tymtam Avatar answered Nov 10 '22 00:11

tymtam