| | | 1 | | using System.Text.Json; |
| | | 2 | | namespace Kestrun.Utilities.Json; |
| | | 3 | | |
| | | 4 | | /// <summary> |
| | | 5 | | /// Helper class for JSON serialization and deserialization using System.Text.Json. |
| | | 6 | | /// </summary> |
| | | 7 | | public static class JsonSerializerHelper |
| | | 8 | | { |
| | 0 | 9 | | private static readonly JsonSerializerOptions Options = new() |
| | 0 | 10 | | { |
| | 0 | 11 | | PropertyNameCaseInsensitive = true, |
| | 0 | 12 | | // If you want enums as strings etc, you can add converters here |
| | 0 | 13 | | // Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } |
| | 0 | 14 | | }; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Deserializes the given JSON string to an object of type T. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <typeparam name="T"> The type of the object to deserialize to. </typeparam> |
| | | 20 | | /// <param name="json"> The JSON string to deserialize. </param> |
| | | 21 | | /// <returns> The deserialized object of type T. </returns> |
| | | 22 | | public static T FromJson<T>(string json) |
| | | 23 | | { |
| | 0 | 24 | | var result = JsonSerializer.Deserialize<T>(json, Options); |
| | 0 | 25 | | return result is null ? throw new JsonException($"Deserialization of type '{typeof(T)}' from JSON failed.") : re |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Deserializes the given JSON string to an object of the specified type. |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="json"> The JSON string to deserialize. </param> |
| | | 32 | | /// <param name="type"> The type to which the JSON string should be deserialized. </param> |
| | | 33 | | /// <returns> The deserialized object. </returns> |
| | 0 | 34 | | public static object FromJson(string json, Type type) => JsonSerializer.Deserialize(json, type, Options)!; |
| | | 35 | | } |