| | 1 | | using System.Security; |
| | 2 | | using System.Text.Encodings.Web; |
| | 3 | | using System.Text.Json; |
| | 4 | | using System.Text.Unicode; |
| | 5 | |
|
| | 6 | | namespace Common.Core.Classes; |
| | 7 | |
|
| | 8 | | /// <summary>Class to provide Json file loading and saving.</summary> |
| | 9 | | public static class JsonHelper |
| | 10 | | { |
| | 11 | | /// <summary>Reads a Json file and populates an object.</summary> |
| | 12 | | /// <typeparam name="T">Generic class or interface.</typeparam> |
| | 13 | | /// <param name="fileName">Json file name.</param> |
| | 14 | | /// <param name="options">Optional Json serializer options.</param> |
| | 15 | | /// <returns><see langword="null"/> is returned if the object could not be populated.</returns> |
| | 16 | | /// <exception cref="ArgumentException">Thrown when one of the arguments provided to a method is not valid.</exception |
| | 17 | | /// <exception cref="IOException">Thrown when an I/O error occurs.</exception> |
| | 18 | | /// <exception cref="NotSupportedException">Thrown when an invoked method is not supported, or when there |
| | 19 | | /// is an attempt to read, seek, or write to a stream that does not support the invoked functionality.</exception> |
| | 20 | | /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue.</exception> |
| | 21 | | /// <exception cref="SecurityException">Thrown when a security error is detected.</exception> |
| | 22 | | /// <exception cref="UnauthorizedAccessException">Thrown when the operating system denies access because of an I/O err |
| | 23 | | public static T? DeserializeFile<T>( string fileName, JsonSerializerOptions? options = null ) where T : class |
| 2 | 24 | | { |
| 2 | 25 | | T? rtn = null; |
| 2 | 26 | | string? json = ReadJsonFromFile( fileName ); |
| 2 | 27 | | options ??= DefaultSerializerOptions(); |
| 2 | 28 | | return json is null ? rtn : DeserializeJson<T>( ref json, options ); |
| 2 | 29 | | } |
| | 30 | |
|
| | 31 | | /// <summary>Reads a Json string and populates an object.</summary> |
| | 32 | | /// <typeparam name="T">Generic class or interface.</typeparam> |
| | 33 | | /// <param name="json">Json string.</param> |
| | 34 | | /// <param name="options">Optional Json serializer options.</param> |
| | 35 | | /// <returns><see langword="null"/> is returned if the object could not be populated.</returns> |
| | 36 | | public static T? DeserializeJson<T>( ref string json, JsonSerializerOptions? options = null ) where T : class |
| 42 | 37 | | { |
| 42 | 38 | | T? rtn = null; |
| | 39 | | try |
| 42 | 40 | | { |
| 42 | 41 | | options ??= DefaultSerializerOptions(); |
| 42 | 42 | | rtn = JsonSerializer.Deserialize<T>( json, options ); |
| 41 | 43 | | } |
| 3 | 44 | | catch( Exception ) { } |
| | 45 | |
|
| 42 | 46 | | return rtn; |
| 42 | 47 | | } |
| | 48 | |
|
| | 49 | | /// <summary>Populates a list of objects from a Json string.</summary> |
| | 50 | | /// <typeparam name="T">Generic class or interface.</typeparam> |
| | 51 | | /// <param name="json">Json string.</param> |
| | 52 | | /// <param name="options">Optional Json serializer options</param> |
| | 53 | | /// <returns>An empty list is returned if the string could not be converted.</returns> |
| | 54 | | public static List<T> DeserializeList<T>( ref string? json, JsonSerializerOptions? options = null ) |
| 2 | 55 | | { |
| 2 | 56 | | List<T> rtn = []; |
| 2 | 57 | | if( json is not null ) |
| 2 | 58 | | { |
| 2 | 59 | | options ??= DefaultSerializerOptions(); |
| | 60 | | try |
| 2 | 61 | | { |
| 2 | 62 | | List<T>? obj = JsonSerializer.Deserialize<List<T>>( json, options ); |
| 4 | 63 | | if( obj is not null ) { rtn = obj; } |
| 1 | 64 | | } |
| 3 | 65 | | catch( Exception ) { } |
| 2 | 66 | | } |
| | 67 | |
|
| 2 | 68 | | return rtn; |
| 2 | 69 | | } |
| | 70 | |
|
| | 71 | | /// <summary>Reads the Json from a file.</summary> |
| | 72 | | /// <param name="fileName">Json file name.</param> |
| | 73 | | /// <returns><see langword="null"/> is returned if the file could not be accessed.</returns> |
| | 74 | | /// <exception cref="ArgumentException">Thrown when one of the arguments provided to a method is not valid.</exception |
| | 75 | | /// <exception cref="IOException">Thrown when an I/O error occurs.</exception> |
| | 76 | | /// <exception cref="NotSupportedException">Thrown when an invoked method is not supported, or when there |
| | 77 | | /// is an attempt to read, seek, or write to a stream that does not support the invoked functionality.</exception> |
| | 78 | | /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue.</exception> |
| | 79 | | /// <exception cref="SecurityException">Thrown when a security error is detected.</exception> |
| | 80 | | /// <exception cref="UnauthorizedAccessException">Thrown when the operating system denies access because of an I/O err |
| | 81 | | public static string? ReadJsonFromFile( string fileName ) |
| 8 | 82 | | { |
| 12 | 83 | | if( string.IsNullOrWhiteSpace( fileName ) ) { return null; } |
| 6 | 84 | | string? json = null; |
| 6 | 85 | | FileInfo fi = new( fileName ); |
| 6 | 86 | | if( fi.Exists ) |
| 5 | 87 | | { |
| 5 | 88 | | using StreamReader sr = new( fi.FullName ); |
| 5 | 89 | | json = sr.ReadToEnd(); |
| 5 | 90 | | } |
| | 91 | |
|
| 6 | 92 | | return json; |
| 8 | 93 | | } |
| | 94 | |
|
| | 95 | | /// <summary>Returns a collection of settings from a Json application settings file.</summary> |
| | 96 | | /// <param name="fileName">Json application settings file name.</param> |
| | 97 | | /// <param name="section">Application settings section to return <i>(case-sensitive)</i>.</param> |
| | 98 | | /// <param name="maxDepth">Maximum depth allowed when parsing JSON data.</param> |
| | 99 | | /// <returns>An empty collection is returned if the settings section could not be found.</returns> |
| | 100 | | /// <remarks>If no section is provided it is assumed that the settings are in the root. |
| | 101 | | /// <br/>Otherwise it is assumed that the section name is case-sensitive and only 3 levels deep.</remarks> |
| | 102 | | public static Dictionary<string, string?> ReadAppSettings( ref string fileName, ref string? section, int maxDepth = 2 |
| 4 | 103 | | { |
| 4 | 104 | | Dictionary<string, string?> rtn = []; |
| | 105 | | try |
| 4 | 106 | | { |
| 4 | 107 | | if( string.IsNullOrEmpty( Path.GetDirectoryName( fileName ) ) ) |
| 1 | 108 | | { |
| 1 | 109 | | fileName = ReflectionHelper.AddCurrentPath( fileName ); |
| 1 | 110 | | } |
| 4 | 111 | | string? json = ReadJsonFromFile( fileName ); |
| 6 | 112 | | if( string.IsNullOrWhiteSpace( json ) ) { return rtn; } |
| 3 | 113 | | JsonDocumentOptions options = new() |
| 3 | 114 | | { |
| 3 | 115 | | AllowTrailingCommas = true, |
| 3 | 116 | | MaxDepth = maxDepth, |
| 3 | 117 | | CommentHandling = JsonCommentHandling.Skip |
| 3 | 118 | | }; |
| 3 | 119 | | using JsonDocument document = JsonDocument.Parse( json, options ); |
| 2 | 120 | | JsonElement coll = document.RootElement; |
| 4 | 121 | | if( !string.IsNullOrEmpty( section ) ) { coll = coll.GetProperty( section ); } |
| 33 | 122 | | foreach( JsonProperty prop in coll.EnumerateObject() ) |
| 15 | 123 | | { |
| 15 | 124 | | if( prop.Value.ValueKind is not JsonValueKind.Object ) |
| 15 | 125 | | { |
| 15 | 126 | | rtn.Add( prop.Name, prop.Value.ToString() ); |
| 15 | 127 | | } |
| 15 | 128 | | } |
| 1 | 129 | | } |
| 6 | 130 | | catch( Exception ) { } |
| | 131 | |
|
| 3 | 132 | | return rtn; |
| 4 | 133 | | } |
| | 134 | |
|
| | 135 | | /// <summary>Writes a Json file of the provided object type.</summary> |
| | 136 | | /// <typeparam name="T">Generic class or interface.</typeparam> |
| | 137 | | /// <param name="obj">Object to save.</param> |
| | 138 | | /// <param name="fileName">Json file name.</param> |
| | 139 | | /// <param name="options">Optional Json serializer options.</param> |
| | 140 | | /// <returns><see langword="true"/> if the object was saved.</returns> |
| | 141 | | /// <exception cref="ArgumentException">Thrown when one of the arguments provided to a method is not valid.</exception |
| | 142 | | /// <exception cref="IOException">Thrown when an I/O error occurs.</exception> |
| | 143 | | /// <exception cref="NotSupportedException">Thrown when an invoked method is not supported, or when there |
| | 144 | | /// is an attempt to read, seek, or write to a stream that does not support the invoked functionality.</exception> |
| | 145 | | /// <exception cref="SecurityException">Thrown when a security error is detected.</exception> |
| | 146 | | /// <exception cref="UnauthorizedAccessException">Thrown when the operating system denies access because of an I/O err |
| | 147 | | public static bool Serialize<T>( T? obj, string fileName, JsonSerializerOptions? options = null ) where T : class |
| 3 | 148 | | { |
| 5 | 149 | | if( obj is null || string.IsNullOrWhiteSpace( fileName ) ) { return false; } |
| 2 | 150 | | options ??= DefaultSerializerOptions(); |
| 2 | 151 | | string json = JsonSerializer.Serialize( obj, options ); |
| 2 | 152 | | File.WriteAllText( fileName, json ); |
| 2 | 153 | | return true; |
| 3 | 154 | | } |
| | 155 | |
|
| | 156 | | /// <summary>Returns a Json string of the provided object type.</summary> |
| | 157 | | /// <typeparam name="T">Generic class or interface.</typeparam> |
| | 158 | | /// <param name="obj">Object to serialize.</param> |
| | 159 | | /// <param name="options">Optional Json serializer options.</param> |
| | 160 | | /// <returns><see langword="null"/> is returned if the serialization fails.</returns> |
| | 161 | | /// <exception cref="NotSupportedException">Thrown when an invoked method is not supported, or when there |
| | 162 | | /// is an attempt to read, seek, or write to a stream that does not support the invoked functionality.</exception> |
| | 163 | | public static string? Serialize<T>( T? obj, JsonSerializerOptions? options = null ) where T : class |
| 10 | 164 | | { |
| 16 | 165 | | if( obj is null ) { return null; } |
| 7 | 166 | | options ??= DefaultSerializerOptions(); |
| 7 | 167 | | return JsonSerializer.Serialize( obj, options ); |
| 10 | 168 | | } |
| | 169 | |
|
| | 170 | | /// <summary>Gets a default set of Json Serializer options.</summary> |
| | 171 | | /// <returns> |
| | 172 | | /// <code> |
| | 173 | | /// AllowTrailingCommas = true |
| | 174 | | /// IgnoreReadOnlyProperties = true |
| | 175 | | /// MaxDepth = 6 |
| | 176 | | /// PropertyNameCaseInsensitive = true |
| | 177 | | /// </code> |
| | 178 | | /// </returns> |
| | 179 | | public static JsonSerializerOptions DefaultSerializerOptions() |
| 69 | 180 | | { |
| 69 | 181 | | return new JsonSerializerOptions |
| 69 | 182 | | { |
| 69 | 183 | | AllowTrailingCommas = true, |
| 69 | 184 | | IgnoreReadOnlyProperties = true, |
| 69 | 185 | | MaxDepth = 6, |
| 69 | 186 | | PropertyNameCaseInsensitive = true, |
| 69 | 187 | | Encoder = JavaScriptEncoder.Create( UnicodeRanges.BasicLatin ), |
| 69 | 188 | | }; |
| 69 | 189 | | } |
| | 190 | | } |