I’m removing Newtonsoft.Json
from a project and replace it with an implementation of System.Text.Json.Serialization
.
The old model uses a JsonArrayAttribute
in combination with CustomCreationConverter<T>
.
class JsonListItemConverter<TListItem>:
CustomCreationConverter<TListItem>
{
public override TListItem Create( Type objectType )
{
return ( TListItem ) FormatterServices.GetSafeUninitializedObject( typeof( TListItem ) );
}
}
interface FooInterface
{
string Value { get; set; }
}
class Foo:
FooInterface
{
public virtual string Value { get; set; }
}
interface BarInterface
{
virtual IList<FooInterface> { get; set; }
}
class Bar:
BarInterface
{
[JsonArray( ItemConverterType = typeof( JsonListItemConverter<Foo> ) )]
public virtual IList<FooInterface> { get; set; }
}
This still enables me to implement against interfaces but deserializes concrete classes.
I’m now looking for an equivalent in System.Net.Json
to replace the now unkown JsonArrayAttribute
.
I assume I’d use JsonConverter
. I found out there’re several converters in System.Text.Json.Serialization.Converters
, like the ListOfTConverter<TCollection, TElement>
. But they are all internal and they are for serializing only.
I’m looking for a solution to deserialize a JSON array into a strongly interfaced collection type like IList<FooInterface>
.
2
Answers
You are trying to replace
Newtonsoft.Json
withSystem.Text.Json
and need to deserialize a JSON array into anIList<FooInterface>
. SinceSystem.Text.Json
doesn’t support deserializing interfaces out of the box, you’ll need to create a custom converter.Explanation:
System.Text.Json
doesn’t natively support deserializing to interface types. By creating a custom converter, you guide the deserialization process to use the concrete class while allowing your code to work with the interface. Some useful tools to visually check Complex JSON.In System.Text.Json, to deserialize a JSON array into a strongly typed collection such as
IList<FooInterface>
, you can utilize a custom converter that implements theJsonConverter
abstract class.Here is an example implementation to achieve this:
JsonConverter<IList<FooInterface>>
:IList<FooInterface>
property in your class:By using a custom
JsonConverter
that reads the JSON array elements and deserializes each element into aFoo
object, you can achieve the desired behavior of deserializing a JSON array into a strongly interfaced collection type likeIList<FooInterface>
.