forked from reactiveui/refit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSystemTextJsonContentSerializer.cs
112 lines (98 loc) · 4.29 KB
/
SystemTextJsonContentSerializer.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Buffers;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Refit.Buffers;
namespace Refit
{
/// <summary>
/// A <see langword="class"/> implementing <see cref="IHttpContentSerializer"/> using the System.Text.Json APIs
/// </summary>
public sealed class SystemTextJsonContentSerializer : IHttpContentSerializer
{
/// <summary>
/// The JSON serialization options to use
/// </summary>
readonly JsonSerializerOptions jsonSerializerOptions;
/// <summary>
/// Creates a new <see cref="SystemTextJsonContentSerializer"/> instance
/// </summary>
public SystemTextJsonContentSerializer() : this(GetDefaultJsonSerializerOptions())
{
}
/// <summary>
/// Creates a new <see cref="SystemTextJsonContentSerializer"/> instance with the specified parameters
/// </summary>
/// <param name="jsonSerializerOptions">The serialization options to use for the current instance</param>
public SystemTextJsonContentSerializer(JsonSerializerOptions jsonSerializerOptions)
{
this.jsonSerializerOptions = jsonSerializerOptions;
}
/// <inheritdoc/>
public HttpContent ToHttpContent<T>(T item)
{
var content = JsonContent.Create(item, options: jsonSerializerOptions);
return content;
}
/// <inheritdoc/>
public async Task<T?> FromHttpContentAsync<T>(HttpContent content, CancellationToken cancellationToken = default)
{
var item = await content.ReadFromJsonAsync<T>(jsonSerializerOptions, cancellationToken).ConfigureAwait(false);
return item;
}
public string? GetFieldNameForProperty(PropertyInfo propertyInfo)
{
if (propertyInfo is null)
throw new ArgumentNullException(nameof(propertyInfo));
return propertyInfo.GetCustomAttributes<JsonPropertyNameAttribute>(true)
.Select(a => a.Name)
.FirstOrDefault();
}
/// <summary>
/// Creates new <see cref="JsonSerializerOptions"/> and fills it with default parameters
/// </summary>
public static JsonSerializerOptions GetDefaultJsonSerializerOptions()
{
var jsonSerializerOptions = new JsonSerializerOptions();
// Default to case insensitive property name matching as that's likely the behavior most users expect
jsonSerializerOptions.PropertyNameCaseInsensitive = true;
jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
jsonSerializerOptions.Converters.Add(new ObjectToInferredTypesConverter());
jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
return jsonSerializerOptions;
}
}
// From https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-5-0#deserialize-inferred-types-to-object-properties
public class ObjectToInferredTypesConverter
: JsonConverter<object>
{
public override object? Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) => reader.TokenType switch
{
JsonTokenType.True => true,
JsonTokenType.False => false,
JsonTokenType.Number when reader.TryGetInt64(out var l) => l,
JsonTokenType.Number => reader.GetDouble(),
JsonTokenType.String when reader.TryGetDateTime(out var datetime) => datetime,
JsonTokenType.String => reader.GetString(),
_ => JsonDocument.ParseValue(ref reader).RootElement.Clone()
};
public override void Write(
Utf8JsonWriter writer,
object objectToWrite,
JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, objectToWrite, objectToWrite.GetType(), options);
}
}