JsonModelConverter
A generic converter which allows JsonSerializer to be able to write and read any models that implement IJsonModel<T>.
using System.ClientModel.Internal;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace System.ClientModel.Primitives
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(new byte[] {
0,
1,
1
})]
public class JsonModelConverter : JsonConverter<IJsonModel<object>>
{
private ModelReaderWriterOptions _options;
[System.Runtime.CompilerServices.Nullable(2)]
private ModelReaderWriterContext _context;
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The constructors of the type being deserialized are dynamically accessed and may be trimmed. Use the constructor which takes ModelReaderWriterContext to be compatible with AOT.")]
public JsonModelConverter()
: this(ModelReaderWriterOptions.Json)
{
}
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The constructors of the type being deserialized are dynamically accessed and may be trimmed. Use the constructor which takes ModelReaderWriterContext to be compatible with AOT.")]
public JsonModelConverter(ModelReaderWriterOptions options)
{
_options = options;
}
public JsonModelConverter(ModelReaderWriterOptions options, ModelReaderWriterContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (options == null)
throw new ArgumentNullException("options");
_context = context;
_options = options;
}
public override bool CanConvert(Type typeToConvert)
{
if (typeof(IJsonModel<object>).IsAssignableFrom(typeToConvert))
return !Attribute.IsDefined(typeToConvert, typeof(JsonConverterAttribute));
return false;
}
[return: System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})]
public override IJsonModel<object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
<>c__DisplayClass6_0 <>c__DisplayClass6_ = default(<>c__DisplayClass6_0);
<>c__DisplayClass6_.<>4__this = this;
<>c__DisplayClass6_.typeToConvert = typeToConvert;
IJsonModel<object> obj = (_context == null) ? <Read>g__NonAotCompatActivate|6_1(ref <>c__DisplayClass6_) : <Read>g__AotCompatActivate|6_0(ref <>c__DisplayClass6_);
if (obj == null)
throw new InvalidOperationException("Either " + <>c__DisplayClass6_.typeToConvert.ToFriendlyName() + " or the PersistableModelProxyAttribute defined needs to implement IJsonModel.");
return (IJsonModel<object>)obj.Create(ref reader, _options);
}
public override void Write(Utf8JsonWriter writer, IJsonModel<object> value, JsonSerializerOptions options)
{
value.Write(writer, _options);
}
}
}