-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJsonSerializerSummary.cs
523 lines (427 loc) · 13 KB
/
JsonSerializerSummary.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
async Task Main()
{
var store = new WareHouse()
{
BrandName = @"Muggy\",
Amount = 1200,
Price = new Dictionary<string,double>
{
["Max"] = 1244.33442,
["Min"] = 988.4323
},
// Fahrenheit or Celsius
Temp = new Temperature(80,celsius:false),
PurchaseDate = new DateTime(2021,10,29),
TemperatureRanges = new Dictionary<string, HighLowTempCelcius>
{
["Cold"] = new HighLowTempCelcius { High = 20, Low = -10 },
["Hot"] = new HighLowTempCelcius { High = 35, Low = 21 },
["Humid"] = new HighLowTempCelcius { High = 60, Low = 36 },
},
// JsonElement issue has been solved by
// new DictionaryStringObjectJsonConverter() implementation
DummyElement = new Dictionary<string,object>
{
["Bool"] = true,
["Null"] = null,
["Text"] = "String",
["Double"] = 332.44,
["Integer"] = 342
},
ItemCategory = Category.Home_Gadget
};
var jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
WriteIndented = true,
IgnoreReadOnlyProperties = true,
//Custom Property Naming Policy
PropertyNamingPolicy = new LowerCaseNamingPolicy(),
// PropertyNamingPolicy = JsonNamingPolicy.CamelCase: built-in policy
// The camel case naming policy for dictionary keys
// applies to serialization only.
// If you deserialize a dictionary, the keys will match the JSON file
// even if you specify JsonNamingPolicy.CamelCase for the DictionaryKeyPolicy.
DictionaryKeyPolicy = new UpperCaseNamingPolicy(),
//Allows comments within the JSON input and ignores them.
//The Utf8JsonReader behaves as if no comments are present.
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
// Writes numbers in string notation as "12"
NumberHandling =
JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.WriteAsString,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
// by default enums are serialized as numbers
// by the help of JsonStringEnumConverter()
// this behaviour may change.
Converters =
{
new JsonStringEnumConverter(), //JsonNamingPolicy is optional
new DateTimeOnlyDateConverter_Turkey(),
new DictionaryStringObjectJsonConverter()
}
};
await using (var stream = new MemoryStream())
{
// Serialize
await JsonSerializer.
SerializeAsync<WareHouse>(stream, store, jsonOptions);
stream.Seek(0,SeekOrigin.Begin);
using var streamReader = new StreamReader(stream,Encoding.UTF8,
false,stream.Capacity);
var script = await streamReader.ReadToEndAsync();
script.Dump();
//Deserialize
stream.Seek(0,SeekOrigin.Begin);
WareHouse wareObject = await JsonSerializer.
DeserializeAsync<WareHouse>(stream,jsonOptions);
wareObject.Dump();
}
}
public class WareHouse : IStorage, ITempConditions
{
[JsonIgnore]
public int ItemId { get; }
public string BrandName { get; set; }
public double Amount { get; set; }
[JsonConverter(typeof(RoundFractionConverter))]
public Dictionary<string,double> Price {get;set;}
public Dictionary<string,object> DummyElement {get;set;}
public DateTime PurchaseDate { get; set; }
public Dictionary<string,HighLowTempCelcius> TemperatureRanges {get;set;}
[JsonPropertyName("KeyWords")] // overrides JsonNamingPolicy.CamelCase
public string[] TempKeyWords => ITempConditions.DefaultTempKeyWords;
[JsonInclude] // include fields, except static, const ones
public byte OptimalTemp = 22;
public Category ItemCategory {get;set;}
public string ItemCategoryString(Category category)
{
return category switch
{
Category.Tool => nameof(Category.Tool),
Category.Hygene => nameof(Category.Hygene),
Category.Home_Gadget => nameof(Category.Home_Gadget),
Category.Food => nameof(Category.Food),
Category.Electronic_Material => nameof(Category.Electronic_Material),
Category.Car_Spare_Part => nameof(Category.Car_Spare_Part),
Category.Bike_Spare_Part => nameof(Category.Bike_Spare_Part),
_ => nameof(Category.None)
};
}
public Temperature Temp {get;set;}
}
public enum Category
{
None,
Food,
Home_Gadget,
Tool,
Electronic_Material,
Car_Spare_Part,
Bike_Spare_Part,
Hygene
}
interface IStorage
{
protected static readonly short SmallSize = 30_000;
protected static readonly int MidSize = 500_000;
protected static readonly int LargeSize = 1_000_000;
public int ItemId { get; }
public string BrandName { get; set; }
public double Amount { get; set; }
public DateTime PurchaseDate { get; set; }
}
interface ITempConditions
{
public Dictionary<string, HighLowTempCelcius> TemperatureRanges { get; set; }
public Temperature Temp {get;set;}
protected static string[] DefaultTempKeyWords => new[] { "Cold", "Humid", "Hot"};
}
public struct HighLowTempCelcius
{
public int High { get; init; }
public int Low { get; init; }
}
//Adding a Custom Property Naming Policy
public class LowerCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) => name.ToLower();
}
// Dictionay Key Policy
public class UpperCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) => name.ToUpper();
}
// [JsonConverter] applied to a property.
// A converter added to the Converters collection.
// [JsonConverter] applied to a custom value type or POCO.
[JsonConverter(typeof(TemperatureConverter))]
public struct Temperature
{
public Temperature(double degrees, bool celsius)
{
Degrees = degrees;
IsCelsius = celsius;
Celcius = celsius ? degrees : Math.Round((degrees - 32)/1.8,2);
}
public double Degrees { get;}
public double Celcius { get;}
public bool IsCelsius { get; }
public bool IsFahrenheit => !IsCelsius;
public override string ToString() =>
$"{Degrees}{(IsCelsius ? "C" : "F")}";
public static Temperature Parse(string input)
{
double degrees = int.Parse(input[..^1]);
bool celsius = input[^1] == 'C';
return new Temperature(degrees, celsius);
}
}
public class TemperatureConverter : JsonConverter<Temperature>
{
public override Temperature Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
Temperature.Parse(reader.GetString());
public override void Write(
Utf8JsonWriter writer,
Temperature temperature,
JsonSerializerOptions options) =>
writer.WriteStringValue(temperature.ToString());
}
public class DateTimeOnlyDateConverter_Turkey : JsonConverter<DateTime>
{
public override DateTime
Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// struct can be assigned by assignment
CultureInfo culture = new CultureInfo("tr-TR");
if (typeToConvert == typeof(DateTime))
{
return DateTime.Parse(reader.GetString(), culture);
}
return new DateTime();
}
public override void
Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
var year = value.Year;
var month = value.Month;
var day = value.Day;
var date = $"{day}/{month}/{year}"; // DateTime format in Turkey
writer.WriteStringValue(date);
}
}
public class RoundFractionConverter : JsonConverter<Dictionary<string, double>>
{
public override Dictionary<string, double>
Read(ref Utf8JsonReader reader,
Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException($"JsonTokenType was of type {reader.TokenType}, only objects are supported");
}
var dictionary = new Dictionary<string, double>();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return dictionary;
}
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException("JsonTokenType was not PropertyName");
}
var propertyName = reader.GetString();
if (string.IsNullOrWhiteSpace(propertyName))
{
throw new JsonException("Failed to get property name");
}
reader.Read();
dictionary.Add(propertyName, GetRoundDictValue(ref reader, options));
}
return dictionary;
}
public override void
Write(Utf8JsonWriter writer,
Dictionary<string, double> value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteNumber("Max",Math.Round(value["Max"],2));
writer.WriteNumber("Min",Math.Round(value["Min"],2));
writer.WriteEndObject();
}
private double
GetRoundDictValue(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Utf8JsonReader readerClone = reader;
if(readerClone.TokenType == JsonTokenType.Number)
{
double value = readerClone.GetDouble();
return Math.Round(value,2);
}
return default(double);
}
}
public class DictionaryStringObjectJsonConverter : JsonConverter<Dictionary<string, object>>
{
public override Dictionary<string, object>
Read(ref Utf8JsonReader reader,
Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException($"JsonTokenType was of type {reader.TokenType}, only objects are supported");
}
var dictionary = new Dictionary<string, object>();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return dictionary;
}
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException("JsonTokenType was not PropertyName");
}
var propertyName = reader.GetString();
if (string.IsNullOrWhiteSpace(propertyName))
{
throw new JsonException("Failed to get property name");
}
reader.Read();
dictionary.Add(propertyName, ExtractValue(ref reader, options));
}
return dictionary;
}
public override void Write(Utf8JsonWriter writer, Dictionary<string, object> value, JsonSerializerOptions options)
{
writer.WriteStartObject();
foreach (var key in value.Keys)
{
HandleValue(writer, key, value[key]);
}
writer.WriteEndObject();
}
private static void HandleValue(Utf8JsonWriter writer, string key, object objectValue)
{
if (key != null)
writer.WritePropertyName(key);
switch (objectValue)
{
case string stringValue:
writer.WriteStringValue(stringValue);
break;
case DateTime dateTime:
writer.WriteStringValue(dateTime);
break;
case long longValue:
writer.WriteNumberValue(longValue);
break;
case int intValue:
writer.WriteNumberValue(intValue);
break;
case float floatValue:
writer.WriteNumberValue(floatValue);
break;
case double doubleValue:
writer.WriteNumberValue(doubleValue);
break;
case decimal decimalValue:
writer.WriteNumberValue(decimalValue);
break;
case bool boolValue:
writer.WriteBooleanValue(boolValue);
break;
case Dictionary<string, object> dict:
writer.WriteStartObject();
foreach (var item in dict)
{
HandleValue(writer, item.Key, item.Value);
}
writer.WriteEndObject();
break;
case object[] array:
writer.WriteStartArray();
foreach (var item in array)
{
HandleValue(writer, item);
}
writer.WriteEndArray();
break;
default:
writer.WriteNullValue();
break;
}
}
private static void HandleValue(Utf8JsonWriter writer, object value)
{
HandleValue(writer, null, value);
}
private object ExtractValue(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
Utf8JsonReader readerClone = reader;
switch (readerClone.TokenType)
{
case JsonTokenType.String:
if (readerClone.TryGetDateTime(out var date))
return date;
return readerClone.GetString();
case JsonTokenType.False:
return false;
case JsonTokenType.True:
return true;
case JsonTokenType.Null:
return null;
case JsonTokenType.Number:
if (readerClone.TryGetInt64(out var result))
return result;
return readerClone.GetDecimal();
case JsonTokenType.StartObject:
return Read(ref readerClone, null, options);
case JsonTokenType.StartArray:
var list = new List<object>();
while (readerClone.Read() && readerClone.TokenType != JsonTokenType.EndArray)
list.Add(ExtractValue(ref readerClone, options));
return list;
default:
throw new JsonException($"'{readerClone.TokenType}' is not supported");
}
}
}
// HttpClient GetFromJsonAsync<T>(requestUri)
namespace HttpClientExtensionMethods
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string Email { get; set; }
}
public class Program
{
public static async Task Main()
{
using HttpClient client = new()
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com")
};
// Get the user information.
User user = await client.GetFromJsonAsync<User>("users/7");
Console.WriteLine($"Id: {user.Id}");
Console.WriteLine($"Name: {user.Name}");
Console.WriteLine($"Username: {user.Username}");
Console.WriteLine($"Email: {user.Email}");
// Post a new user.
HttpResponseMessage response =
await client.PostAsJsonAsync("users", user);
Console.WriteLine(
$"{(response.IsSuccessStatusCode ? "Success" : "Error")}"
+ $"- {response.StatusCode}");
}
}
}