@@ -366,4 +366,67 @@ public class TestClass
366366
367367BUT watch out for `Nullable < T > ` value types when you do that , they won 't work
368368correctly until .NET 5 . [There is a bug in
369- System .Text .Json ](https :// github.com/dotnet/runtime/pull/32006).
369+ System .Text .Json ](https :// github.com/dotnet/runtime/pull/32006).
370+
371+ ## TypeConverters
372+
373+ The .NET runtime provides the
374+ [TypeConverter ](https :// docs.microsoft.com/en-us/dotnet/api/system.componentmodel.typeconverter?view=net-5.0)
375+ class in the System .ComponentModel namespace as a generic mechanism for
376+ converting between different types at runtime . `TypeConverter ` is applied to a
377+ target type using an [attribute
378+ decoration ](https :// docs.microsoft.com/en-us/dotnet/api/system.componentmodel.typeconverterattribute?view=net-5.0)
379+ pattern , much like `JsonConverter `, but it is not supported by the
380+ System .Text .Json engine (as of .NET 5).
381+
382+ The `JsonTypeConverterAdapterFactory ` is provided to add support for using a
383+ `TypeConverter ` to [de ]serialize a given type through System .Text .Json . Note :
384+ The `TypeConverter ` being used must support `string ` as a to destination & from
385+ source .
386+
387+ ```csharp
388+ [JsonConverter (typeof (JsonTypeConverterAdapterFactory ))]
389+ [TypeConverter (typeof (MyCustomTypeConverter ))]
390+ public class MyClass
391+ {
392+ public string PropertyA { get ; }
393+
394+ public string PropertyB { get ; }
395+
396+ internal MyClass (string propertyA , string propertyB )
397+ {
398+ PropertyA = propertyA ;
399+ PropertyB = propertyB ;
400+ }
401+ }
402+
403+ public class MyCustomTypeConverter : TypeConverter
404+ {
405+ public override bool CanConvertFrom (ITypeDescriptorContext context , Type sourceType ) =>
406+ sourceType == typeof (string ) || base .CanConvertFrom (context , sourceType );
407+
408+ public override object ConvertFrom (ITypeDescriptorContext context , CultureInfo culture , object value )
409+ {
410+ if (value is string str )
411+ {
412+ string [] data = str .Split ('|' );
413+ return new MyClass (data [0 ], data [1 ]);
414+ }
415+
416+ return base .ConvertFrom (context , culture , value );
417+ }
418+
419+ public override bool CanConvertTo (ITypeDescriptorContext context , Type destinationType )
420+ => destinationType == typeof (string ) || base .CanConvertTo (context , destinationType );
421+
422+ public override object ConvertTo (ITypeDescriptorContext context , CultureInfo culture , object value , Type destinationType )
423+ {
424+ if (value is MyClass myClass && destinationType == typeof (string ))
425+ {
426+ return $" {myClass .PropertyA }|{myClass .PropertyB }" ;
427+ }
428+
429+ return base .ConvertTo (context , culture , value , destinationType );
430+ }
431+ }
432+ ```
0 commit comments