-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathCustomJsonWriterConverterFactory.cs
48 lines (37 loc) · 1.32 KB
/
CustomJsonWriterConverterFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Elastic.Clients.Elasticsearch.Serialization;
internal sealed class CustomJsonWriterConverterFactory : JsonConverterFactory
{
private readonly IElasticsearchClientSettings _settings;
public CustomJsonWriterConverterFactory(IElasticsearchClientSettings settings) => _settings = settings;
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
var interfaces = typeToConvert.GetInterfaces();
var canConvert = false;
foreach (var item in interfaces)
{
var type = item.UnderlyingSystemType;
if (type == typeof(ICustomJsonWriter))
canConvert = true;
}
return canConvert;
}
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var converter = (JsonConverter)Activator.CreateInstance(
typeof(CustomJsonWriterConverter<>).MakeGenericType(typeToConvert),
BindingFlags.Instance | BindingFlags.Public,
args: new object[] { _settings },
binder: null,
culture: null)!;
return converter;
}
}