├── .gitignore
├── LICENSE
├── Open.Serialization.Json.Newtonsoft
├── .editorconfig
├── CamelCaseJson.cs
├── Converters
│ ├── JsonDecimalConverter.cs
│ ├── JsonDecimalRoundingConverter.cs
│ ├── JsonDoubleRoundingConverter.cs
│ ├── JsonNullableDecimalConverter.cs
│ ├── JsonNullableDecimalRoundingConverter.cs
│ ├── JsonNullableDoubleConverter.cs
│ ├── JsonNullableDoubleRoundingConverter.cs
│ └── JsonValueConverterBase.cs
├── GlobalSuppressions.cs
├── JsonSerializerFactory.cs
├── JsonSerializerInternal.cs
├── Open.Serialization.Json.Newtonsoft.csproj
├── RelaxedJson.cs
└── SerializationExtensions.cs
├── Open.Serialization.Json.System
├── .editorconfig
├── CamelCaseJson.cs
├── CaseSensitiveJson.cs
├── Converters
│ ├── JsonDecimalConverter.cs
│ ├── JsonDecimalRoundingConverter.cs
│ ├── JsonDoubleRoundingConverter.cs
│ ├── JsonNullableDecimalConverter.cs
│ ├── JsonNullableDecimalRoundingConverter.cs
│ ├── JsonNullableDoubleConverter.cs
│ ├── JsonNullableDoubleRoundingConverter.cs
│ ├── JsonValueConverterBase.cs
│ └── Readme.md
├── JsonSerializerFactory.cs
├── JsonSerializerInternal.cs
├── Open.Serialization.Json.System.csproj
├── RelaxedJson.cs
└── SerializationsExtensions.cs
├── Open.Serialization.Json.Utf8Json
├── .editorconfig
├── JsonSerializerFactory.cs
├── JsonSerializerInternal.cs
├── Open.Serialization.Json.Utf8Json.csproj
└── SerializationExtensions.cs
├── Open.Serialization.Json
├── IJsonAsyncObjectSerializer.cs
├── IJsonAsyncSerializer.cs
├── IJsonDeserialize.cs
├── IJsonDeserializeAsync.cs
├── IJsonDeserializeObject.cs
├── IJsonDeserializeObjectAsync.cs
├── IJsonObjectSerializationFactory.cs
├── IJsonObjectSerializer.cs
├── IJsonObjectSerializerFactory.cs
├── IJsonSerializationFactory.cs
├── IJsonSerializationOptions.cs
├── IJsonSerialize.cs
├── IJsonSerializeAsync.cs
├── IJsonSerializeObject.cs
├── IJsonSerializeObjectAsync.cs
├── IJsonSerializer.cs
├── IJsonSerializerFactory.cs
├── JsonObjectSerializer.cs
├── JsonObjectSerializerBase.cs
├── JsonSerializationOptions.cs
├── JsonSerializer.cs
├── JsonSerializerBase.cs
├── Open.Serialization.Json.csproj
└── Open.Serialization.Json.xml
├── Open.Serialization.Tests
├── DefaultImplementationTests.cs
├── Newtonsoft
│ └── JsonExtensionTests.cs
├── Open.Serialization.Tests.csproj
├── ParityTests.cs
├── SampleModel.cs
└── System
│ └── JsonExtensionTests.cs
├── Open.Serialization.sln
├── Open.Serialization
├── .editorconfig
├── DefaultMethods.cs
├── Extensions
│ └── SerializationExtensions.cs
├── IDeserialize.cs
├── IDeserializeAsync.cs
├── IDeserializeObject.cs
├── IDeserializeObjectAsync.cs
├── IObjectSerializer.cs
├── ISerialize.cs
├── ISerializeAsync.cs
├── ISerializeObject.cs
├── ISerializeObjectAsync.cs
├── ISerializer.cs
├── ObjectSerializer.cs
├── ObjectSerializerBase.cs
├── Open.Serialization.csproj
├── Open.Serialization.xml
├── Serializer.cs
└── SerializerBase.cs
├── README.md
└── logo.png
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 | /.vscode
332 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2020 electricessence (Oren F.) All rights reserved
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.cs]
2 |
3 | # CA1303: Do not pass literals as localized parameters
4 | dotnet_diagnostic.CA1303.severity = silent
5 |
6 | # CA1062: Validate arguments of public methods
7 | dotnet_diagnostic.CA1062.severity = suggestion
8 |
9 | # CA1305: Specify IFormatProvider
10 | dotnet_diagnostic.CA1305.severity = silent
11 |
12 | # CA1307: Specify StringComparison
13 | dotnet_diagnostic.CA1307.severity = suggestion
14 |
15 | # CS1591: Missing XML comment for publicly visible type or member
16 | dotnet_diagnostic.CS1591.severity = silent
17 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/CamelCaseJson.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Serialization;
3 |
4 | namespace Open.Serialization.Json.Newtonsoft;
5 |
6 | public static class CamelCaseJson
7 | {
8 | public static JsonSerializerSettings Default(bool indent = false)
9 | {
10 | var options = RelaxedJson.Options(indent);
11 | options.ContractResolver = new CamelCasePropertyNamesContractResolver()
12 | {
13 | NamingStrategy = new CamelCaseNamingStrategy() { ProcessDictionaryKeys = false }
14 | };
15 | return options;
16 | }
17 |
18 | public static JsonSerializerSettings Minimal(bool indent = false)
19 | {
20 | var options = Default(indent);
21 | options.NullValueHandling = NullValueHandling.Ignore;
22 | return options;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonDecimalConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Diagnostics.Contracts;
4 |
5 | namespace Open.Serialization.Json.Newtonsoft.Converters;
6 |
7 | ///
8 | /// A converter for ensuring proper standardized processing of decimals.
9 | ///
10 | public class JsonDecimalConverter : JsonValueConverterBase
11 | {
12 | ///
13 | /// Constructs a .
14 | ///
15 | protected JsonDecimalConverter()
16 | {
17 | // Prevent unnecessary replication.
18 | }
19 |
20 | ///
21 | /// Shared instance of this converter.
22 | ///
23 | public static readonly JsonDecimalConverter Instance
24 | = new();
25 |
26 | ///
27 | #if NETSTANDARD2_1
28 | [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("value")]
29 | #endif
30 | public static string? Normalize(decimal? value)
31 | => Normalize(value?.ToString());
32 |
33 | ///
34 | /// Normalizes a decimal by removing any unnecessary trailing zeros or decimal.
35 | ///
36 | #if NETSTANDARD2_1
37 | [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("decimalString")]
38 | #endif
39 | public static string? Normalize(string? decimalString)
40 | => string.IsNullOrEmpty(decimalString) || decimalString!.IndexOf('.') == -1
41 | ? decimalString
42 | : decimalString.AsSpan().TrimEnd('0').TrimEnd('.').ToString();
43 |
44 | ///
45 | public override decimal ReadJson(JsonReader reader, Type objectType, decimal existingValue, bool hasExistingValue, JsonSerializer serializer)
46 | {
47 | if (reader is null) throw new ArgumentNullException(nameof(reader));
48 | Contract.EndContractBlock();
49 |
50 | return ConvertToDecimal(reader.Value!);
51 | }
52 |
53 | ///
54 | public override void WriteJson(JsonWriter writer, decimal value, JsonSerializer serializer)
55 | {
56 | if (writer is null) throw new ArgumentNullException(nameof(writer));
57 | Contract.EndContractBlock();
58 |
59 | writer.WriteRawValue(Normalize(value));
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonDecimalRoundingConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace Open.Serialization.Json.Newtonsoft.Converters;
5 |
6 | ///
7 | /// Converter for decimals that rounds to a maximum number of digits after the decimal.
8 | ///
9 | public class JsonDecimalRoundingConverter : JsonDecimalConverter
10 | {
11 | ///
12 | /// The maximum number of digits after the decimal.
13 | ///
14 | public int Maximum { get; }
15 |
16 | ///
17 | /// Constructs a .
18 | ///
19 | /// The maximum number of digits after the decimal.
20 | /// If the maximum is less than zero.
21 | public JsonDecimalRoundingConverter(int maximum)
22 | {
23 | if (maximum < 0)
24 | throw new ArgumentOutOfRangeException(nameof(maximum), maximum, "Must be at least zero.");
25 | Maximum = maximum;
26 | }
27 |
28 | ///
29 | public override decimal ReadJson(JsonReader reader, Type objectType, decimal existingValue, bool hasExistingValue, JsonSerializer serializer)
30 | => Math.Round(base.ReadJson(reader, objectType, existingValue, hasExistingValue, serializer), Maximum);
31 |
32 | ///
33 | public override void WriteJson(JsonWriter writer, decimal value, JsonSerializer serializer)
34 | => base.WriteJson(writer, Math.Round(value, Maximum), serializer);
35 | }
36 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonDoubleRoundingConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Diagnostics.Contracts;
4 | using System.Numerics;
5 |
6 | namespace Open.Serialization.Json.Newtonsoft.Converters;
7 |
8 | ///
9 | /// Converter for doubles that rounds to a maximum number of digits after the decimal.
10 | ///
11 | public class JsonDoubleRoundingConverter : JsonValueConverterBase
12 | {
13 | ///
14 | /// The maximum number of digits after the decimal.
15 | ///
16 | public int Maximum { get; }
17 |
18 | ///
19 | /// Constructs a .
20 | ///
21 | /// The maximum number of digits after the decimal.
22 | /// If the maximum is less than zero.
23 | public JsonDoubleRoundingConverter(int maximum)
24 | {
25 | if (maximum < 0)
26 | throw new ArgumentOutOfRangeException(nameof(maximum), maximum, "Must be at least zero.");
27 | Maximum = maximum;
28 | }
29 |
30 | public override double ReadJson(JsonReader reader, Type objectType, double existingValue, bool hasExistingValue, JsonSerializer serializer)
31 | {
32 | if (reader is null) throw new ArgumentNullException(nameof(reader));
33 | Contract.EndContractBlock();
34 |
35 | return reader.Value switch
36 | {
37 | double d => Math.Round(d, Maximum),
38 | decimal d => ConvertToDouble(Math.Round(d, Maximum)),
39 | sbyte i => i,
40 | byte i => i,
41 | short i => i,
42 | ushort i => i,
43 | int i => i,
44 | uint i => i,
45 | long i => i,
46 | ulong i => i,
47 | BigInteger i => (double)i,
48 | _ => Math.Round(ConvertToDouble(reader.Value!), Maximum),
49 | };
50 | }
51 |
52 | public override void WriteJson(JsonWriter writer, double value, JsonSerializer serializer)
53 | {
54 | if (writer is null) throw new ArgumentNullException(nameof(writer));
55 | Contract.EndContractBlock();
56 |
57 | writer.WriteValue(Math.Round(value, Maximum));
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonNullableDecimalConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Diagnostics.Contracts;
4 |
5 | namespace Open.Serialization.Json.Newtonsoft.Converters;
6 |
7 | public class JsonNullableDecimalConverter : JsonValueConverterBase
8 | {
9 | protected JsonNullableDecimalConverter()
10 | {
11 | // Prevent unnecessary replication.
12 | }
13 |
14 | public static readonly JsonNullableDecimalConverter Instance
15 | = new();
16 |
17 | ///
18 | public override decimal? ReadJson(JsonReader reader, Type objectType, decimal? existingValue, bool hasExistingValue, JsonSerializer serializer)
19 | {
20 | if (reader is null) throw new ArgumentNullException(nameof(reader));
21 | Contract.EndContractBlock();
22 |
23 | return reader.TokenType switch
24 | {
25 | JsonToken.Null => null,
26 | JsonToken.Undefined => null,
27 | _ => ConvertToDecimal(reader.Value!),
28 | };
29 | }
30 |
31 | ///
32 | public override void WriteJson(JsonWriter writer, decimal? value, JsonSerializer serializer)
33 | {
34 | if (writer is null) throw new ArgumentNullException(nameof(writer));
35 | Contract.EndContractBlock();
36 |
37 | writer.WriteRawValue(JsonDecimalConverter.Normalize(value));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonNullableDecimalRoundingConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace Open.Serialization.Json.Newtonsoft.Converters;
5 |
6 | ///
7 | /// Converter for nullable decimals that rounds to a maximum number of digits after the decimal.
8 | ///
9 | public class JsonNullableDecimalRoundingConverter : JsonNullableDecimalConverter
10 | {
11 | ///
12 | /// The maximum number of digits after the decimal.
13 | ///
14 | public int Maximum { get; }
15 |
16 | ///
17 | /// Constructs a .
18 | ///
19 | /// The maximum number of digits after the decimal.
20 | /// If the maximum is less than zero.
21 | public JsonNullableDecimalRoundingConverter(int maximum)
22 | {
23 | if (maximum < 0)
24 | throw new ArgumentOutOfRangeException(nameof(maximum), maximum, "Must be at least zero.");
25 | Maximum = maximum;
26 | }
27 |
28 | public override decimal? ReadJson(JsonReader reader, Type objectType, decimal? existingValue, bool hasExistingValue, JsonSerializer serializer)
29 | {
30 | var value = base.ReadJson(reader, objectType, existingValue, hasExistingValue, serializer);
31 | return value.HasValue ? Math.Round(value.Value, Maximum) : value;
32 | }
33 |
34 | public override void WriteJson(JsonWriter writer, decimal? value, JsonSerializer serializer)
35 | {
36 | if (value.HasValue)
37 | value = Math.Round(value.Value, Maximum);
38 |
39 | base.WriteJson(writer, value, serializer);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonNullableDoubleConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Diagnostics.Contracts;
4 |
5 | namespace Open.Serialization.Json.Newtonsoft.Converters;
6 |
7 | public class JsonNullableDoubleConverter : JsonValueConverterBase
8 | {
9 | protected JsonNullableDoubleConverter()
10 | {
11 | // Prevent unnecessary replication.
12 | }
13 |
14 | public static readonly JsonNullableDoubleConverter Instance
15 | = new();
16 |
17 | public override double? ReadJson(JsonReader reader, Type objectType, double? existingValue, bool hasExistingValue, JsonSerializer serializer)
18 | {
19 | if (reader is null) throw new ArgumentNullException(nameof(reader));
20 | Contract.EndContractBlock();
21 |
22 | return reader.TokenType switch
23 | {
24 | JsonToken.Null => null,
25 | JsonToken.Undefined => null,
26 | _ => ConvertToDouble(reader.Value!)
27 | };
28 | }
29 |
30 | public override void WriteJson(JsonWriter writer, double? value, JsonSerializer serializer)
31 | {
32 | if (writer is null) throw new ArgumentNullException(nameof(writer));
33 | Contract.EndContractBlock();
34 |
35 | if (value.HasValue) writer.WriteValue(value.Value);
36 | else writer.WriteRawValue(null);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonNullableDoubleRoundingConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace Open.Serialization.Json.Newtonsoft.Converters;
5 |
6 | public class JsonNullableDoubleRoundingConverter : JsonNullableDoubleConverter
7 | {
8 | public int Maximum { get; }
9 | public JsonNullableDoubleRoundingConverter(int maximum)
10 | {
11 | if (maximum < 0)
12 | throw new ArgumentOutOfRangeException(nameof(maximum), maximum, "Must be at least zero.");
13 | Maximum = maximum;
14 | }
15 |
16 | public override double? ReadJson(JsonReader reader, Type objectType, double? existingValue, bool hasExistingValue, JsonSerializer serializer)
17 | {
18 | var value = base.ReadJson(reader, objectType, existingValue, hasExistingValue, serializer);
19 | return value.HasValue ? Math.Round(value.Value, Maximum) : value;
20 | }
21 |
22 | public override void WriteJson(JsonWriter writer, double? value, JsonSerializer serializer)
23 | {
24 | if (value.HasValue)
25 | value = Math.Round(value.Value, Maximum);
26 |
27 | base.WriteJson(writer, value, serializer);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Converters/JsonValueConverterBase.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Numerics;
4 |
5 | namespace Open.Serialization.Json.Newtonsoft.Converters;
6 |
7 | ///
8 | /// Base JsonConverter for NewtsonSoft.Json.
9 | ///
10 | public abstract class JsonValueConverterBase : JsonConverter
11 | {
12 | // Avoids stack overflow.
13 | private static readonly JsonSerializer Deserializer = JsonSerializer.Create();
14 |
15 | ///
16 | public override T ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
17 | => Deserializer.Deserialize(reader)!;
18 |
19 | ///
20 | public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
21 | #pragma warning disable CA1062 // Validate arguments of public methods
22 | => writer.WriteRawValue(value?.ToString());
23 | #pragma warning restore CA1062 // Validate arguments of public methods
24 |
25 | ///
26 | /// Special convert to decimal from object.
27 | ///
28 | protected static decimal ConvertToDecimal(object value) => value switch
29 | {
30 | decimal d => d,
31 | BigInteger i => (decimal)i,
32 | IConvertible _ => Convert.ToDecimal(value),
33 | _ => throw new ArgumentException("Unable to convert to decimal.", nameof(value)),
34 | };
35 |
36 | ///
37 | /// Special convert to decimal from object.
38 | ///
39 | protected static double ConvertToDouble(object value) => value switch
40 | {
41 | double d => d,
42 | BigInteger i => (double)i,
43 | IConvertible _ => Convert.ToDouble(value),
44 | _ => throw new ArgumentException("Unable to convert to double.", nameof(value)),
45 | };
46 | }
47 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // This file is used by Code Analysis to maintain SuppressMessage
2 | // attributes that are applied to this project.
3 | // Project-level suppressions either have no target or are given
4 | // a specific target and scoped to a namespace, type, member, etc.
5 |
6 | using System.Diagnostics.CodeAnalysis;
7 |
8 | [assembly: SuppressMessage("Globalization", "CA1307:Specify StringComparison for clarity", Justification = "", Scope = "member", Target = "~M:Open.Serialization.Json.Newtonsoft.Converters.JsonDecimalConverter.Normalize(System.String)~System.String")]
9 | [assembly: SuppressMessage("Usage", "CA2249:Consider using 'string.Contains' instead of 'string.IndexOf'", Justification = "", Scope = "member", Target = "~M:Open.Serialization.Json.Newtonsoft.Converters.JsonDecimalConverter.Normalize(System.String)~System.String")]
10 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/JsonSerializerFactory.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Serialization;
3 | using System;
4 | using System.Threading;
5 |
6 | namespace Open.Serialization.Json.Newtonsoft;
7 |
8 | public class JsonSerializerFactory : IJsonSerializerFactory, IJsonObjectSerializerFactory
9 | {
10 | static readonly JsonSerializerSettings DefaultOptions = RelaxedJson.Options();
11 | readonly JsonSerializerSettings _settings;
12 | public JsonSerializerFactory(JsonSerializerSettings? defaultOptions)
13 | {
14 | _settings = defaultOptions?.Clone() ?? DefaultOptions;
15 | }
16 |
17 | public JsonSerializerFactory() : this(null)
18 | {
19 | }
20 |
21 | JsonSerializerInternal? _defaultSerializer;
22 | internal JsonSerializerInternal DefaultSerializer
23 | => LazyInitializer.EnsureInitialized(ref _defaultSerializer, () => new JsonSerializerInternal(_settings))!;
24 |
25 | static JsonSerializerFactory? _default;
26 | public static JsonSerializerFactory Default
27 | => LazyInitializer.EnsureInitialized(ref _default)!;
28 |
29 | #if NETSTANDARD2_1
30 | [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("options")]
31 | #endif
32 | public JsonSerializerSettings? GetJsonSerializerSettings(IJsonSerializationOptions? options = null, bool caseSensitive = false)
33 | {
34 | if (caseSensitive)
35 | throw new NotSupportedException("Newtonsoft does not support case-sensitive deserialization.");
36 |
37 | if (options is null) return null;
38 |
39 | if (options.CamelCaseKeys == true && options.CamelCaseProperties != true)
40 | throw new NotSupportedException("Camel casing keys but not properties is not supported.");
41 |
42 | var o = _settings.Clone();
43 | if (options.CamelCaseKeys == true)
44 | {
45 | o.ContractResolver = new DefaultContractResolver
46 | {
47 | NamingStrategy = new CamelCaseNamingStrategy
48 | {
49 | ProcessDictionaryKeys = true
50 | }
51 | };
52 | }
53 | else if (options.CamelCaseProperties == true)
54 | {
55 | o.ContractResolver = new CamelCasePropertyNamesContractResolver();
56 | }
57 | else if (options.CamelCaseProperties == false)
58 | {
59 | o.ContractResolver = new DefaultContractResolver();
60 | }
61 |
62 | if (options.OmitNull.HasValue)
63 | o.NullValueHandling = options.OmitNull.Value ? NullValueHandling.Ignore : NullValueHandling.Include;
64 |
65 | if (options.Indent.HasValue)
66 | o.Formatting = options.Indent.Value ? Formatting.Indented : Formatting.None;
67 |
68 | return o;
69 | }
70 |
71 | internal JsonSerializerInternal GetSerializerInternal(IJsonSerializationOptions? options = null, bool caseSensitive = false)
72 | {
73 | var o = GetJsonSerializerSettings(options, caseSensitive);
74 | return o is null ? DefaultSerializer : new JsonSerializerInternal(o);
75 | }
76 |
77 | ///
78 | /// Returns an .
79 | ///
80 | public IJsonSerializer GetSerializer(IJsonSerializationOptions? options = null, bool caseSensitive = false)
81 | => GetSerializerInternal(options, caseSensitive);
82 |
83 | ///
84 | /// Returns an .
85 | ///
86 | public IJsonObjectSerializer GetObjectSerializer(IJsonSerializationOptions? options = null, bool caseSensitive = false)
87 | => GetSerializerInternal(options, caseSensitive);
88 | }
89 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/JsonSerializerInternal.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace Open.Serialization.Json.Newtonsoft;
5 |
6 | internal class JsonSerializerInternal : JsonObjectSerializerBase, IJsonSerializer
7 | {
8 | readonly JsonSerializerSettings _settings;
9 | internal JsonSerializerInternal(JsonSerializerSettings settings)
10 | {
11 | _settings = settings;
12 | }
13 |
14 | public override T Deserialize(string value)
15 | => JsonConvert.DeserializeObject(value, _settings)!;
16 |
17 | public override string Serialize(T item)
18 | => JsonConvert.SerializeObject(item, _settings);
19 |
20 | public override object? Deserialize(string value, Type type)
21 | => JsonConvert.DeserializeObject(value, type);
22 |
23 | public override string Serialize(object? item, Type type)
24 | => JsonConvert.SerializeObject(item, type, _settings);
25 |
26 | public new JsonSerializer Cast()
27 | => new(Deserialize, Serialize, DeserializeAsync, SerializeAsync);
28 | }
29 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/Open.Serialization.Json.Newtonsoft.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0; netstandard2.1
5 | true
6 | latest
7 | enable
8 | true
9 | electricessence
10 |
11 | Extentions and DI utilities for Newtonsoft.Json.
12 |
13 | Part of the "Open" set of libraries.
14 |
15 | serialization;json;newtonsoft
16 | © electricessence (Oren F.) All rights reserved.
17 | MIT
18 | https://github.com/Open-NET-Libraries/Open.Serialization
19 | https://github.com/Open-NET-Libraries/Open.Serialization
20 | git
21 | 3.0.0
22 |
23 | MIT
24 | true
25 | true
26 | snupkg
27 | logo.png
28 | true
29 | README.md
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | True
41 |
42 |
43 |
44 | True
45 | \
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/RelaxedJson.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Serialization;
3 | using Open.Serialization.Json.Newtonsoft.Converters;
4 |
5 | namespace Open.Serialization.Json.Newtonsoft;
6 |
7 | ///
8 | /// Shortcut for accessing default relaxed JSON options.
9 | ///
10 | public static class RelaxedJson
11 | {
12 | internal static JsonSerializerSettings Options(
13 | bool indent = false)
14 | => new JsonSerializerSettings()
15 | {
16 | Formatting = indent ? Formatting.Indented : Formatting.None,
17 | FloatParseHandling = FloatParseHandling.Decimal,
18 | ContractResolver = new DefaultContractResolver()
19 | {
20 | NamingStrategy = new DefaultNamingStrategy() { ProcessDictionaryKeys = false }
21 | }
22 | }
23 | .AddConverter(JsonNullableDoubleConverter.Instance)
24 | .NormalizeDecimals();
25 |
26 | ///
27 | /// Returns an .s
28 | ///
29 | public static IJsonDeserialize GetDeserializer()
30 | => DeserializerOptions.GetSerializer();
31 |
32 | ///
33 | /// Returns an .
34 | ///
35 | public static IJsonDeserialize GetDeserializer()
36 | => DeserializerOptions.GetSerializer();
37 |
38 | static readonly JsonSerializerSettings DeserializerOptions
39 | = Options().SetNullValueHandling(NullValueHandling.Ignore);
40 |
41 | ///
42 | public static TValue Deserialize(string value)
43 | => DeserializerOptions.Deserialize(value);
44 | }
45 |
--------------------------------------------------------------------------------
/Open.Serialization.Json.Newtonsoft/SerializationExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using Newtonsoft.Json;
3 | using Open.Serialization.Json.Newtonsoft.Converters;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.Contracts;
7 | using System.Linq;
8 |
9 | namespace Open.Serialization.Json.Newtonsoft;
10 |
11 | ///
12 | /// Extensions for Newtonsof.Json serialization with Open.Serialization.Json.
13 | ///
14 | public static class SerializationExtensions
15 | {
16 | ///
17 | /// Adds a generic serializer and non-generic to the service collection.
18 | ///
19 | /// The service collection.
20 | /// The options overrides.
21 | /// The service collection.
22 | public static IServiceCollection AddJsonSerializer(this IServiceCollection services, IJsonSerializationOptions? options = null)
23 | {
24 | var factory = JsonSerializerFactory.Default;
25 | var serializer = factory.GetSerializerInternal(options);
26 | services.AddSingleton(serializer);
27 | services.AddSingleton(serializer);
28 | return services;
29 | }
30 |
31 | ///
32 | /// Adds a generic serializer to the service collection.
33 | ///
34 | ///
35 | public static IServiceCollection AddJsonSerializer(this IServiceCollection services, IJsonSerializationOptions? options = null)
36 | {
37 | var factory = JsonSerializerFactory.Default;
38 | services.AddSingleton>(factory.GetSerializerInternal(options).Cast());
39 | return services;
40 | }
41 |
42 | public static Func GetDeserialize(this JsonSerializerSettings settings)
43 | => json => JsonConvert.DeserializeObject(json, settings)!;
44 |
45 | public static Func GetSerialize(this JsonSerializerSettings settings)
46 | => item => JsonConvert.SerializeObject(item, settings);
47 |
48 | public static Func