| | 1 | | using System.Reflection; |
| | 2 | | using System.Text.Json; |
| | 3 | | using Cff.Effect.Abstractions; |
| | 4 | |
|
| | 5 | | namespace Cff.Effect.Json; |
| | 6 | |
|
| 14 | 7 | | internal readonly record struct Json(JsonSerializerOptions JsonSerializerOptions) : IJson |
| | 8 | | { |
| | 9 | | public string Serialize<T>(T msg) where T : notnull |
| 5 | 10 | | { |
| 5 | 11 | | var assembly = msg.GetType().Assembly.GetName().Name; |
| 5 | 12 | | var type = msg.GetType().FullName!; |
| | 13 | |
|
| 5 | 14 | | return @$"{{""A"":""{assembly}"",""T"":""{type}"",""V"":{JsonSerializer.Serialize(msg, JsonSerializerOptions)}}} |
| 5 | 15 | | } |
| | 16 | |
|
| | 17 | | public Task<object?> DeserializeAsync(Stream stream, CancellationToken ct) |
| 0 | 18 | | { |
| 0 | 19 | | var q = (JsonSerializerOptions option) => |
| 0 | 20 | | from doc in JsonDocument.ParseAsync(stream, cancellationToken: ct) |
| 0 | 21 | | let root = doc.RootElement |
| 0 | 22 | | let assembly = root.GetProperty("A").GetString() |
| 0 | 23 | | let typeName = root.GetProperty("T").GetString() |
| 0 | 24 | | let type = Assembly.Load(assembly).GetType(typeName) |
| 0 | 25 | | select root.GetProperty("V").Deserialize(type, option); |
| | 26 | |
|
| 0 | 27 | | return q(JsonSerializerOptions); |
| 0 | 28 | | } |
| | 29 | |
|
| | 30 | | public object? Deserialize(string jsonString) |
| 2 | 31 | | { |
| 2 | 32 | | var root = JsonDocument.Parse(jsonString).RootElement; |
| | 33 | |
|
| 2 | 34 | | var assembly = root.GetProperty("A").GetString(); |
| 2 | 35 | | var typeName = root.GetProperty("T").GetString(); |
| | 36 | |
|
| 2 | 37 | | var type = Assembly.Load(assembly!).GetType(typeName!); |
| | 38 | |
|
| 2 | 39 | | return root.GetProperty("V").Deserialize(type!, JsonSerializerOptions); |
| 2 | 40 | | } |
| | 41 | | } |
| | 42 | |
|