Is there a way to combine custom converters from different projects? #81894
-
System.Text.Json Given I have an object A in project X, with its own custom converters Finally I have object C (in project Z), which has object A and B as properties, and also has its own custom converters (for the other properties) Instead of adding the custom converters of manually in Converters = { new ConverterA, new ConverterB} etc., what I want to do is dynamically get the Converters from Project X and Y and set it in Project Z's JsonSerializerOptions. What is the recommend way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
with NewtonSoft, I can easily add all of the converters in a list and then set it like: var converters = new List() { JsonSerializerOptions ProjectZSerializerOptions = new JsonSerializerOptions() {Converters = converters} Or is the best practice to just copy paste the converters from the Project X and project Y? |
Beta Was this translation helpful? Give feedback.
-
The public static ListExtensions
{
public static void AddRange(this IList<T> list, IEnumerable<T> range)
{
foreach (var T item in range)
list.Add(item);
}
} And then use that to combine converters from different var options = new JsonSerializerOptions();
options.Converters.AddRange(options2.Converters);
options.Converters.AddRange(options3.Converters); |
Beta Was this translation helpful? Give feedback.
The
JsonSerializerOptions.Converters
property is an IList, so there's noAddRange
method you can use out of the box. I would recommend writing your own extension method:And then use that to combine converters from different
JsonSerializerOptions
: