-
Notifications
You must be signed in to change notification settings - Fork 15
/
HashidsJsonConverter.cs
44 lines (37 loc) · 1.27 KB
/
HashidsJsonConverter.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
using HashidsNet;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace AspNetCore.Hashids.Json
{
public class HashidsJsonConverter : JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
var stringValue = reader.GetString();
var hashid = GetHashids(options).Decode(stringValue);
if (hashid.Length == 0)
{
throw new JsonException("Invalid hash.");
}
return hashid[0];
}
else if (reader.TokenType == JsonTokenType.Number)
{
return reader.GetInt32();
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
writer.WriteStringValue(GetHashids(options).Encode(value));
}
private IHashids GetHashids(JsonSerializerOptions options)
{
return options.GetServiceProvider().GetRequiredService<IHashids>();
}
}
}