-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathJsonSerializationMethodsBuilder.cs
1209 lines (1049 loc) · 66 KB
/
JsonSerializationMethodsBuilder.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml;
using AutoRest.CSharp.Common.Input;
using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions;
using AutoRest.CSharp.Common.Output.Expressions.Statements;
using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions;
using AutoRest.CSharp.Common.Output.Models;
using AutoRest.CSharp.Common.Output.Models.Types;
using AutoRest.CSharp.Generation.Types;
using AutoRest.CSharp.Generation.Writers;
using AutoRest.CSharp.Input.Source;
using AutoRest.CSharp.Mgmt.Decorator;
using AutoRest.CSharp.Mgmt.Output;
using AutoRest.CSharp.Output.Models;
using AutoRest.CSharp.Output.Models.Serialization;
using AutoRest.CSharp.Output.Models.Serialization.Json;
using AutoRest.CSharp.Output.Models.Serialization.Xml;
using AutoRest.CSharp.Output.Models.Shared;
using AutoRest.CSharp.Output.Models.Types;
using AutoRest.CSharp.Utilities;
using Azure;
using Azure.Core;
using Azure.ResourceManager.Resources.Models;
using Microsoft.CodeAnalysis;
using static AutoRest.CSharp.Common.Output.Models.Snippets;
using SerializationFormat = AutoRest.CSharp.Output.Models.Serialization.SerializationFormat;
namespace AutoRest.CSharp.Common.Output.Builders
{
internal static class JsonSerializationMethodsBuilder
{
public static IEnumerable<Method> BuildJsonSerializationMethods(SerializableObjectType model, JsonObjectSerialization json)
{
var jsonModelInterface = json.IJsonModelInterface;
var typeOfT = jsonModelInterface.Arguments[0];
var useModelReaderWriter = Configuration.UseModelReaderWriter;
// void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
var writer = new Utf8JsonWriterExpression(KnownParameters.Serializations.Utf8JsonWriter);
if (useModelReaderWriter)
{
yield return new
(
new MethodSignature(Configuration.ApiTypes.IUtf8JsonSerializableWriteName, null, null, MethodSignatureModifiers.None, null, null, new[] { KnownParameters.Serializations.Utf8JsonWriter }, ExplicitInterface: Configuration.ApiTypes.IUtf8JsonSerializableType),
This.CastTo(jsonModelInterface).Invoke(nameof(IJsonModel<object>.Write), writer, ModelReaderWriterOptionsExpression.Wire)
);
}
else
{
yield return new
(
new MethodSignature(Configuration.ApiTypes.IUtf8JsonSerializableWriteName, null, null, MethodSignatureModifiers.None, null, null, new[] { KnownParameters.Serializations.Utf8JsonWriter }, ExplicitInterface: Configuration.ApiTypes.IUtf8JsonSerializableType),
WriteObject(json, writer, null)
);
}
if (useModelReaderWriter)
{
// void IJsonModel<T>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
var options = new ModelReaderWriterOptionsExpression(KnownParameters.Serializations.Options);
yield return new
(
new MethodSignature(nameof(IJsonModel<object>.Write), null, null, MethodSignatureModifiers.None, null, null, new[] { KnownParameters.Serializations.Utf8JsonWriter, KnownParameters.Serializations.Options }, ExplicitInterface: jsonModelInterface),
WriteObject(json, writer, options)
);
// T IJsonModel<T>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
var reader = (ValueExpression)KnownParameters.Serializations.Utf8JsonReader;
yield return new
(
new MethodSignature(nameof(IJsonModel<object>.Create), null, null, MethodSignatureModifiers.None, typeOfT, null, new[] { KnownParameters.Serializations.Utf8JsonReader, KnownParameters.Serializations.Options }, ExplicitInterface: jsonModelInterface),
new MethodBodyStatement[]
{
Serializations.ValidateJsonFormat(options, json.IPersistableModelTInterface),
// using var document = JsonDocument.ParseValue(ref reader);
UsingDeclare("document", JsonDocumentExpression.ParseValue(reader), out var docVariable),
// return DeserializeXXX(doc.RootElement, options);
Return(SerializableObjectTypeExpression.Deserialize(model, docVariable.RootElement, options))
}
);
// if the model is a struct, it needs to implement IJsonModel<object> as well which leads to another 2 methods
if (json.IJsonModelObjectInterface is { } jsonModelObjectInterface)
{
// void IJsonModel<object>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IJsonModel<object>.Write), null, null, MethodSignatureModifiers.None, null, null, new[] { KnownParameters.Serializations.Utf8JsonWriter, KnownParameters.Serializations.Options }, ExplicitInterface: jsonModelObjectInterface),
This.CastTo(jsonModelInterface).Invoke(nameof(IJsonModel<object>.Write), writer, options)
);
// object IJsonModel<object>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IJsonModel<object>.Create), null, null, MethodSignatureModifiers.None, typeof(object), null, new[] { KnownParameters.Serializations.Utf8JsonReader, KnownParameters.Serializations.Options }, ExplicitInterface: jsonModelObjectInterface),
This.CastTo(jsonModelInterface).Invoke(nameof(IJsonModel<object>.Create), reader, options)
);
}
}
}
public static IEnumerable<Method> BuildIModelMethods(SerializableObjectType model, JsonObjectSerialization? json, XmlObjectSerialization? xml)
{
// we do not need this if model reader writer feature is not enabled
if (!Configuration.UseModelReaderWriter)
yield break;
var iModelTInterface = json?.IPersistableModelTInterface ?? xml?.IPersistableModelTInterface;
var iModelObjectInterface = json?.IPersistableModelObjectInterface ?? xml?.IPersistableModelObjectInterface;
// if we have json serialization, we must have this interface.
// if we have xml serialization, we must have this interface.
// therefore this type should never be null - because we cannot get here when json and xml both are null
Debug.Assert(iModelTInterface != null);
var typeOfT = iModelTInterface.Arguments[0];
var options = new ModelReaderWriterOptionsExpression(KnownParameters.Serializations.Options);
// BinaryData IPersistableModel<T>.Write(ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.Write), null, null, MethodSignatureModifiers.None, typeof(BinaryData), null, new[] { KnownParameters.Serializations.Options }, ExplicitInterface: iModelTInterface),
BuildModelWriteMethodBody(json, xml, options, iModelTInterface).ToArray()
);
// T IPersistableModel<T>.Create(BinaryData data, ModelReaderWriterOptions options)
var data = new BinaryDataExpression(KnownParameters.Serializations.Data);
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.Create), null, null, MethodSignatureModifiers.None, typeOfT, null, new[] { KnownParameters.Serializations.Data, KnownParameters.Serializations.Options }, ExplicitInterface: iModelTInterface),
BuildModelCreateMethodBody(model, json != null, xml != null, data, options, iModelTInterface).ToArray()
);
// ModelReaderWriterFormat IPersistableModel<T>.GetFormatFromOptions(ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.GetFormatFromOptions), null, null, MethodSignatureModifiers.None, typeof(string), null, new[] { KnownParameters.Serializations.Options }, ExplicitInterface: iModelTInterface),
xml != null ? Serializations.XmlFormat : Serializations.JsonFormat
);
// if the model is a struct, it needs to implement IPersistableModel<object> as well which leads to another 2 methods
if (iModelObjectInterface is not null)
{
// BinaryData IPersistableModel<object>.Write(ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.Write), null, null, MethodSignatureModifiers.None, typeof(BinaryData), null, new[] { KnownParameters.Serializations.Options }, ExplicitInterface: iModelObjectInterface),
// => (IPersistableModel<T>this).Write(options);
This.CastTo(iModelTInterface).Invoke(nameof(IPersistableModel<object>.Write), options)
);
// object IPersistableModel<object>.Create(BinaryData data, ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.Create), null, null, MethodSignatureModifiers.None, typeof(object), null, new[] { KnownParameters.Serializations.Data, KnownParameters.Serializations.Options }, ExplicitInterface: iModelObjectInterface),
// => (IPersistableModel<T>this).Read(options);
This.CastTo(iModelTInterface).Invoke(nameof(IPersistableModel<object>.Create), data, options)
);
// ModelReaderWriterFormat IPersistableModel<object>.GetFormatFromOptions(ModelReaderWriterOptions options)
yield return new
(
new MethodSignature(nameof(IPersistableModel<object>.GetFormatFromOptions), null, null, MethodSignatureModifiers.None, typeof(string), null, new[] { KnownParameters.Serializations.Options }, ExplicitInterface: iModelObjectInterface),
// => (IPersistableModel<T>this).GetFormatFromOptions(options);
This.CastTo(iModelTInterface).Invoke(nameof(IPersistableModel<object>.GetFormatFromOptions), options)
);
}
static IEnumerable<MethodBodyStatement> BuildModelWriteMethodBody(JsonObjectSerialization? json, XmlObjectSerialization? xml, ModelReaderWriterOptionsExpression options, CSharpType iModelTInterface)
{
// var format = options.Format == "W" ? GetFormatFromOptions(options) : options.Format;
yield return Serializations.GetConcreteFormat(options, iModelTInterface, out var format);
yield return EmptyLine;
var switchStatement = new SwitchStatement(format);
if (json != null)
{
var jsonCase = new SwitchCase(Serializations.JsonFormat,
Return(new InvokeStaticMethodExpression(typeof(ModelReaderWriter), nameof(ModelReaderWriter.Write), new[] { This, options }))
);
switchStatement.Add(jsonCase);
}
if (xml != null)
{
/* using MemoryStream stream = new MemoryStream();
using XmlWriter writer = XmlWriter.Create(stream);
((IXmlSerializable)this).Write(writer, null);
writer.Flush();
// in the implementation of MemoryStream, `stream.Position` could never exceed `int.MaxValue`, therefore this if is redundant, we just need to keep the else branch
//if (stream.Position > int.MaxValue)
//{
// return BinaryData.FromStream(stream);
//}
//else
//{
return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position));
//}
*/
var xmlCase = new SwitchCase(Serializations.XmlFormat,
new MethodBodyStatement[]
{
UsingDeclare("stream", typeof(MemoryStream), New.Instance(typeof(MemoryStream)), out var stream),
UsingDeclare("writer", typeof(XmlWriter), new InvokeStaticMethodExpression(typeof(XmlWriter), nameof(XmlWriter.Create), new[] { stream }), out var xmlWriter),
new InvokeInstanceMethodStatement(null, xml.WriteXmlMethodName, new[] { xmlWriter, Null, options }, false),
xmlWriter.Invoke(nameof(XmlWriter.Flush)).ToStatement(),
// return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position));
Return(New.Instance(typeof(BinaryData),
InvokeStaticMethodExpression.Extension(
typeof(MemoryExtensions),
nameof(MemoryExtensions.AsMemory),
stream.Invoke(nameof(MemoryStream.GetBuffer)),
new[] { Int(0), stream.Property(nameof(Stream.Position)).CastTo(typeof(int)) }
)))
}, addScope: true); // using statement must have a scope, if we do not have the addScope parameter here, the generated code will not compile
switchStatement.Add(xmlCase);
}
// default case
/*
* throw new FormatException($"The model {nameof(T)} does not support '{options.Format}' format.");
*/
var typeOfT = iModelTInterface.Arguments[0];
var defaultCase = SwitchCase.Default(
Serializations.ThrowValidationFailException(options.Format, typeOfT)
);
switchStatement.Add(defaultCase);
yield return switchStatement;
}
static IEnumerable<MethodBodyStatement> BuildModelCreateMethodBody(SerializableObjectType model, bool hasJson, bool hasXml, BinaryDataExpression data, ModelReaderWriterOptionsExpression options, CSharpType iModelTInterface)
{
// var format = options.Format == "W" ? GetFormatFromOptions(options) : options.Format;
yield return Serializations.GetConcreteFormat(options, iModelTInterface, out var format);
yield return EmptyLine;
var switchStatement = new SwitchStatement(format);
if (hasJson)
{
/* using var document = JsonDocument.ParseValue(ref reader);
* return DeserializeXXX(doc.RootElement, options);
*/
var jsonCase = new SwitchCase(Serializations.JsonFormat,
new MethodBodyStatement[]
{
UsingDeclare("document", JsonDocumentExpression.Parse(data), out var docVariable),
Return(SerializableObjectTypeExpression.Deserialize(model, docVariable.RootElement, options))
}, addScope: true); // using statement must have a scope, if we do not have the addScope parameter here, the generated code will not compile
switchStatement.Add(jsonCase);
}
if (hasXml)
{
// return DeserializeXmlCollection(XElement.Load(data.ToStream()), options);
var xmlCase = new SwitchCase(Serializations.XmlFormat,
Return(SerializableObjectTypeExpression.Deserialize(model, XElementExpression.Load(data.ToStream()), options)));
switchStatement.Add(xmlCase);
}
// default case
/*
* throw new InvalidOperationException($"The model {nameof(T)} does not support '{options.Format}' format.");
*/
var typeOfT = iModelTInterface.Arguments[0];
var defaultCase = SwitchCase.Default(
Serializations.ThrowValidationFailException(options.Format, typeOfT)
);
switchStatement.Add(defaultCase);
yield return switchStatement;
}
}
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static MethodBodyStatement[] WriteObject(JsonObjectSerialization serialization, Utf8JsonWriterExpression utf8JsonWriter, ModelReaderWriterOptionsExpression? options)
=> new[]
{
Serializations.ValidateJsonFormat(options, serialization.IPersistableModelTInterface),
utf8JsonWriter.WriteStartObject(),
WriteProperties(utf8JsonWriter, serialization.Properties, options).ToArray(),
SerializeAdditionalProperties(utf8JsonWriter, options, serialization.AdditionalProperties),
utf8JsonWriter.WriteEndObject()
};
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static IEnumerable<MethodBodyStatement> WriteProperties(Utf8JsonWriterExpression utf8JsonWriter, IEnumerable<JsonPropertySerialization> properties, ModelReaderWriterOptionsExpression? options)
{
foreach (JsonPropertySerialization property in properties)
{
if (property.ValueSerialization == null)
{
// Flattened property
yield return Serializations.WrapInCheckNotWire(
property,
options?.Format,
new[]
{
utf8JsonWriter.WritePropertyName(property.SerializedName),
utf8JsonWriter.WriteStartObject(),
WriteProperties(utf8JsonWriter, property.PropertySerializations!, options).ToArray(),
utf8JsonWriter.WriteEndObject(),
});
}
else if (property.SerializedType is { IsNullable: true })
{
var checkPropertyIsInitialized = TypeFactory.IsCollectionType(property.SerializedType) && !TypeFactory.IsReadOnlyMemory(property.SerializedType) && property.IsRequired
? And(NotEqual(property.Value, Null), InvokeOptional.IsCollectionDefined(property.Value))
: NotEqual(property.Value, Null);
yield return Serializations.WrapInCheckNotWire(
property,
options?.Format,
InvokeOptional.WrapInIsDefined(
property,
new IfElseStatement(checkPropertyIsInitialized,
WritePropertySerialization(utf8JsonWriter, property),
utf8JsonWriter.WriteNull(property.SerializedName)
))
);
}
else
{
yield return Serializations.WrapInCheckNotWire(
property,
options?.Format,
InvokeOptional.WrapInIsDefined(property, WritePropertySerialization(utf8JsonWriter, property)));
}
}
}
private static MethodBodyStatement WritePropertySerialization(Utf8JsonWriterExpression utf8JsonWriter, JsonPropertySerialization serialization)
{
return new[]
{
utf8JsonWriter.WritePropertyName(serialization.SerializedName),
serialization.CustomSerializationMethodName is {} serializationMethodName
? InvokeCustomSerializationMethod(serializationMethodName, utf8JsonWriter)
: SerializeExpression(utf8JsonWriter, serialization.ValueSerialization, serialization.EnumerableValue ?? serialization.Value)
};
}
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static MethodBodyStatement SerializeAdditionalProperties(Utf8JsonWriterExpression utf8JsonWriter, ModelReaderWriterOptionsExpression? options, JsonAdditionalPropertiesSerialization? additionalProperties)
{
if (additionalProperties is null)
{
return EmptyStatement;
}
var additionalPropertiesExpression = new DictionaryExpression(additionalProperties.Type.Arguments[0], additionalProperties.Type.Arguments[1], additionalProperties.Value);
MethodBodyStatement statement = new ForeachStatement("item", additionalPropertiesExpression, out KeyValuePairExpression item)
{
utf8JsonWriter.WritePropertyName(item.Key),
SerializeExpression(utf8JsonWriter, additionalProperties.ValueSerialization, item.Value)
};
// if it should be excluded in wire serialization, it is a raw data field and we need to check if it is null
// otherwise it is the public AdditionalProperties property, we always instantiate it therefore we do not need to check null.
statement = additionalProperties.ShouldExcludeInWireSerialization ?
new IfStatement(NotEqual(additionalPropertiesExpression, Null))
{
statement
} : statement;
return Serializations.WrapInCheckNotWire(
additionalProperties,
options?.Format,
statement);
}
public static MethodBodyStatement SerializeExpression(Utf8JsonWriterExpression utf8JsonWriter, JsonSerialization? serialization, ValueExpression expression)
=> serialization switch
{
JsonArraySerialization array => SerializeArray(utf8JsonWriter, array, new EnumerableExpression(TypeFactory.GetElementType(array.ImplementationType), expression)),
JsonDictionarySerialization dictionary => SerializeDictionary(utf8JsonWriter, dictionary, new DictionaryExpression(dictionary.Type.Arguments[0], dictionary.Type.Arguments[1], expression)),
JsonValueSerialization value => SerializeValue(utf8JsonWriter, value, expression),
_ => throw new NotSupportedException()
};
private static MethodBodyStatement SerializeArray(Utf8JsonWriterExpression utf8JsonWriter, JsonArraySerialization arraySerialization, EnumerableExpression array)
{
return new[]
{
utf8JsonWriter.WriteStartArray(),
new ForeachStatement("item", array, out var item)
{
CheckCollectionItemForNull(utf8JsonWriter, arraySerialization.ValueSerialization, item),
SerializeExpression(utf8JsonWriter, arraySerialization.ValueSerialization, item)
},
utf8JsonWriter.WriteEndArray()
};
}
private static MethodBodyStatement SerializeDictionary(Utf8JsonWriterExpression utf8JsonWriter, JsonDictionarySerialization dictionarySerialization, DictionaryExpression dictionary)
{
return new[]
{
utf8JsonWriter.WriteStartObject(),
new ForeachStatement("item", dictionary, out KeyValuePairExpression keyValuePair)
{
utf8JsonWriter.WritePropertyName(keyValuePair.Key),
CheckCollectionItemForNull(utf8JsonWriter, dictionarySerialization.ValueSerialization, keyValuePair.Value),
SerializeExpression(utf8JsonWriter, dictionarySerialization.ValueSerialization, keyValuePair.Value)
},
utf8JsonWriter.WriteEndObject()
};
}
private static MethodBodyStatement SerializeValue(Utf8JsonWriterExpression utf8JsonWriter, JsonValueSerialization valueSerialization, ValueExpression value)
{
if (valueSerialization.Type.SerializeAs is not null)
{
return SerializeFrameworkTypeValue(utf8JsonWriter, valueSerialization, value, valueSerialization.Type.SerializeAs);
}
if (valueSerialization.Type.IsFrameworkType)
{
return SerializeFrameworkTypeValue(utf8JsonWriter, valueSerialization, value, valueSerialization.Type.FrameworkType);
}
switch (valueSerialization.Type.Implementation)
{
case SystemObjectType systemObjectType when IsCustomJsonConverterAdded(systemObjectType.SystemType):
if (valueSerialization.Options == JsonSerializationOptions.UseManagedServiceIdentityV3)
{
return new[]
{
Var("serializeOptions", New.JsonSerializerOptions(), out var serializeOptions),
InvokeJsonSerializerSerializeMethod(utf8JsonWriter, value, serializeOptions)
};
}
return InvokeJsonSerializerSerializeMethod(utf8JsonWriter, value);
case ObjectType:
return utf8JsonWriter.WriteObjectValue(value);
case EnumType { IsIntValueType: true, IsExtensible: false } enumType:
return utf8JsonWriter.WriteNumberValue(new CastExpression(value.NullableStructValue(valueSerialization.Type), enumType.ValueType));
case EnumType { IsNumericValueType: true } enumType:
return utf8JsonWriter.WriteNumberValue(new EnumExpression(enumType, value.NullableStructValue(valueSerialization.Type)).ToSerial());
case EnumType enumType:
return utf8JsonWriter.WriteStringValue(new EnumExpression(enumType, value.NullableStructValue(valueSerialization.Type)).ToSerial());
default:
throw new NotSupportedException($"Cannot build serialization expression for type {valueSerialization.Type}, please add `CodeGenMemberSerializationHooks` to specify the serialization of this type with the customized property");
}
}
private static MethodBodyStatement SerializeFrameworkTypeValue(Utf8JsonWriterExpression utf8JsonWriter, JsonValueSerialization valueSerialization, ValueExpression value, Type valueType)
{
if (valueType == typeof(JsonElement))
{
return new JsonElementExpression(value).WriteTo(utf8JsonWriter);
}
if (valueType == typeof(Nullable<>))
{
valueType = valueSerialization.Type.Arguments[0].FrameworkType;
}
value = value.NullableStructValue(valueSerialization.Type);
if (valueType == typeof(decimal) || valueType == typeof(double) || valueType == typeof(float) || valueType == typeof(long) || valueType == typeof(int) || valueType == typeof(short))
{
return utf8JsonWriter.WriteNumberValue(value);
}
if (valueType == typeof(object))
{
return utf8JsonWriter.WriteObjectValue(value);
}
// These are string-like types that could implicitly convert to string type
if (valueType == typeof(string) || valueType == typeof(char) || valueType == typeof(Guid) || valueType == typeof(ResourceIdentifier) || valueType == typeof(ResourceType) || valueType == typeof(AzureLocation))
{
return utf8JsonWriter.WriteStringValue(value);
}
if (valueType == typeof(bool))
{
return utf8JsonWriter.WriteBooleanValue(value);
}
if (valueType == typeof(byte[]))
{
return utf8JsonWriter.WriteBase64StringValue(value, valueSerialization.Format.ToFormatSpecifier());
}
if (valueType == typeof(DateTimeOffset) || valueType == typeof(DateTime) || valueType == typeof(TimeSpan))
{
var format = valueSerialization.Format.ToFormatSpecifier();
if (valueSerialization.Format is SerializationFormat.Duration_Seconds)
{
return utf8JsonWriter.WriteNumberValue(InvokeConvert.ToInt32(new TimeSpanExpression(value).ToString(format)));
}
if (valueSerialization.Format is SerializationFormat.Duration_Seconds_Float)
{
return utf8JsonWriter.WriteNumberValue(InvokeConvert.ToDouble(new TimeSpanExpression(value).ToString(format)));
}
if (valueSerialization.Format is SerializationFormat.DateTime_Unix)
{
return utf8JsonWriter.WriteNumberValue(value, format);
}
return format is not null
? utf8JsonWriter.WriteStringValue(value, format)
: utf8JsonWriter.WriteStringValue(value);
}
// These are string-like types that cannot implicitly convert to string type, therefore we need to call ToString on them
if (valueType == typeof(ETag) || valueType == typeof(ContentType) || valueType == typeof(IPAddress) || valueType == typeof(RequestMethod) || valueType == typeof(ExtendedLocationType))
{
return utf8JsonWriter.WriteStringValue(value.InvokeToString());
}
if (valueType == typeof(Uri))
{
return utf8JsonWriter.WriteStringValue(new MemberExpression(value, nameof(Uri.AbsoluteUri)));
}
if (valueType == typeof(BinaryData))
{
var binaryDataValue = new BinaryDataExpression(value);
if (valueSerialization.Format is SerializationFormat.Bytes_Base64 or SerializationFormat.Bytes_Base64Url)
{
return utf8JsonWriter.WriteBase64StringValue(new BinaryDataExpression(value).ToArray(), valueSerialization.Format.ToFormatSpecifier());
}
return new IfElsePreprocessorDirective
(
"NET6_0_OR_GREATER",
utf8JsonWriter.WriteRawValue(value),
new UsingScopeStatement(typeof(JsonDocument), "document", JsonDocumentExpression.Parse(binaryDataValue), out var jsonDocumentVar)
{
InvokeJsonSerializerSerializeMethod(utf8JsonWriter, new JsonDocumentExpression(jsonDocumentVar).RootElement)
}
);
}
if (IsCustomJsonConverterAdded(valueType))
{
return InvokeJsonSerializerSerializeMethod(utf8JsonWriter, value);
}
throw new NotSupportedException($"Framework type {valueType} serialization not supported, please add `CodeGenMemberSerializationHooks` to specify the serialization of this type with the customized property");
}
private static MethodBodyStatement CheckCollectionItemForNull(Utf8JsonWriterExpression utf8JsonWriter, JsonSerialization valueSerialization, ValueExpression value)
=> CollectionItemRequiresNullCheckInSerialization(valueSerialization)
? new IfStatement(Equal(value, Null)) { utf8JsonWriter.WriteNullValue(), Continue }
: EmptyStatement;
public static Method? BuildDeserialize(TypeDeclarationOptions declaration, JsonObjectSerialization serialization, INamedTypeSymbol? existingType)
{
var methodName = $"Deserialize{declaration.Name}";
var signature = Configuration.UseModelReaderWriter ?
new MethodSignature(methodName, null, null, MethodSignatureModifiers.Internal | MethodSignatureModifiers.Static, serialization.Type, null, new[] { KnownParameters.Serializations.JsonElement, KnownParameters.Serializations.OptionalOptions }) :
new MethodSignature(methodName, null, null, MethodSignatureModifiers.Internal | MethodSignatureModifiers.Static, serialization.Type, null, new[] { KnownParameters.Serializations.JsonElement });
if (SourceInputHelper.TryGetExistingMethod(existingType, signature, out _))
{
return null;
}
return Configuration.UseModelReaderWriter ?
new Method(signature, BuildDeserializeBody(serialization, new JsonElementExpression(KnownParameters.Serializations.JsonElement), new ModelReaderWriterOptionsExpression(KnownParameters.Serializations.OptionalOptions)).ToArray()) :
new Method(signature, BuildDeserializeBody(serialization, new JsonElementExpression(KnownParameters.Serializations.JsonElement), null).ToArray());
}
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static IEnumerable<MethodBodyStatement> BuildDeserializeBody(JsonObjectSerialization serialization, JsonElementExpression jsonElement, ModelReaderWriterOptionsExpression? options)
{
// fallback to Default options if it is null
if (options != null)
{
yield return AssignIfNull(options, ModelReaderWriterOptionsExpression.Wire);
yield return EmptyLine;
}
if (!serialization.Type.IsValueType) // only return null for reference type (e.g. no enum)
{
yield return new IfStatement(jsonElement.ValueKindEqualsNull())
{
Return(Null)
};
}
var discriminator = serialization.Discriminator;
if (discriminator is not null && discriminator.HasDescendants)
{
yield return new IfStatement(jsonElement.TryGetProperty(discriminator.SerializedName, out var discriminatorElement))
{
new SwitchStatement(discriminatorElement.GetString(), GetDiscriminatorCases(jsonElement, discriminator).ToArray())
};
}
// we redirect the deserialization to the `DefaultObjectType` (the unknown version of the discriminated set) if possible.
// We could only do this when there is a discriminator, and the discriminator does not have a value (having a value indicating it is the child instead of base), and there is an unknown default object type to fall back, and I am not that fallback type.
if (discriminator is { Value: null, DefaultObjectType: { } defaultObjectType } && !serialization.Type.Equals(defaultObjectType.Type))
{
yield return Return(GetDeserializeImplementation(discriminator.DefaultObjectType.Type.Implementation, jsonElement, null));
}
else
{
yield return WriteObjectInitialization(serialization, jsonElement, options).ToArray();
}
}
private static IEnumerable<SwitchCase> GetDiscriminatorCases(JsonElementExpression element, ObjectTypeDiscriminator discriminator)
{
foreach (var implementation in discriminator.Implementations)
{
yield return new SwitchCase(Literal(implementation.Key), Return(GetDeserializeImplementation(implementation.Type.Implementation, element, null)), true);
}
}
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static IEnumerable<MethodBodyStatement> WriteObjectInitialization(JsonObjectSerialization serialization, JsonElementExpression element, ModelReaderWriterOptionsExpression? options)
{
// this is the first level of object hierarchy
// collect all properties and initialize the dictionary
var propertyVariables = new Dictionary<JsonPropertySerialization, VariableReference>();
CollectPropertiesForDeserialization(propertyVariables, serialization.Properties);
var additionalProperties = serialization.AdditionalProperties;
if (additionalProperties != null)
{
propertyVariables.Add(additionalProperties, new VariableReference(additionalProperties.Value.Type, additionalProperties.SerializationConstructorParameterName));
}
bool isThisTheDefaultDerivedType = serialization.Type.Equals(serialization.Discriminator?.DefaultObjectType?.Type);
foreach (var variable in propertyVariables)
{
if (serialization.Discriminator?.SerializedName == variable.Key.SerializedName &&
isThisTheDefaultDerivedType &&
serialization.Discriminator.Value is not null &&
(!serialization.Discriminator.Property.ValueType.IsEnum || serialization.Discriminator.Property.ValueType.Implementation is EnumType { IsExtensible: true }))
{
var defaultValue = serialization.Discriminator.Value.Value.Value?.ToString();
yield return Declare(variable.Value, Literal(defaultValue));
}
else
{
yield return Declare(variable.Value, Default);
}
}
var shouldTreatEmptyStringAsNull = Configuration.ModelsToTreatEmptyStringAsNull.Contains(serialization.Type.Name);
var objAdditionalProperties = serialization.AdditionalProperties;
if (objAdditionalProperties != null)
{
var dictionary = new VariableReference(objAdditionalProperties.Type, "additionalPropertiesDictionary");
yield return Declare(dictionary, New.Instance(objAdditionalProperties.Type));
yield return new ForeachStatement("property", element.EnumerateObject(), out var property)
{
DeserializeIntoObjectProperties(serialization.Properties, objAdditionalProperties, new JsonPropertyExpression(property), new DictionaryExpression(objAdditionalProperties.Type.Arguments[0], objAdditionalProperties.Type.Arguments[1], dictionary), options, propertyVariables, shouldTreatEmptyStringAsNull).ToArray()
};
yield return Assign(propertyVariables[objAdditionalProperties], dictionary);
}
else
{
yield return new ForeachStatement("property", element.EnumerateObject(), out var property)
{
DeserializeIntoObjectProperties(serialization.Properties, new JsonPropertyExpression(property), propertyVariables, shouldTreatEmptyStringAsNull)
};
}
var parameterValues = propertyVariables.ToDictionary(v => v.Key.SerializationConstructorParameterName, v => GetOptional(v.Key, v.Value));
var parameters = serialization.ConstructorParameters
.Select(p => parameterValues[p.Name])
.ToArray();
yield return Return(New.Instance(serialization.Type, parameters));
}
// TODO -- make the options parameter non-nullable again when we remove the `UseModelReaderWriter` flag.
private static IEnumerable<MethodBodyStatement> DeserializeIntoObjectProperties(IEnumerable<JsonPropertySerialization> propertySerializations, JsonAdditionalPropertiesSerialization additionalPropertiesSerialization, JsonPropertyExpression jsonProperty, DictionaryExpression dictionary, ModelReaderWriterOptionsExpression? options, IReadOnlyDictionary<JsonPropertySerialization, VariableReference> propertyVariables, bool shouldTreatEmptyStringAsNull)
{
yield return DeserializeIntoObjectProperties(propertySerializations, jsonProperty, propertyVariables, shouldTreatEmptyStringAsNull);
// in the case here, this line returns an empty statement, we only want the value here
yield return DeserializeValue(additionalPropertiesSerialization.ValueSerialization!, jsonProperty.Value, out var value);
var additionalPropertiesStatement = dictionary.Add(jsonProperty.Name, value);
yield return Serializations.WrapInCheckNotWire(
additionalPropertiesSerialization,
options?.Format,
additionalPropertiesStatement);
}
private static MethodBodyStatement DeserializeIntoObjectProperties(IEnumerable<JsonPropertySerialization> propertySerializations, JsonPropertyExpression jsonProperty, IReadOnlyDictionary<JsonPropertySerialization, VariableReference> propertyVariables, bool shouldTreatEmptyStringAsNull)
=> propertySerializations
.Select(p => new IfStatement(jsonProperty.NameEquals(p.SerializedName))
{
DeserializeIntoObjectProperty(p, jsonProperty, propertyVariables, shouldTreatEmptyStringAsNull)
})
.ToArray();
private static MethodBodyStatement DeserializeIntoObjectProperty(JsonPropertySerialization jsonPropertySerialization, JsonPropertyExpression jsonProperty, IReadOnlyDictionary<JsonPropertySerialization, VariableReference> propertyVariables, bool shouldTreatEmptyStringAsNull)
{
// write the deserialization hook
if (jsonPropertySerialization.CustomDeserializationMethodName is { } deserializationMethodName)
{
return new[]
{
CreatePropertyNullCheckStatement(jsonPropertySerialization, jsonProperty, propertyVariables, shouldTreatEmptyStringAsNull),
InvokeCustomDeserializationMethod(deserializationMethodName, jsonProperty, propertyVariables[jsonPropertySerialization].Declaration),
Continue
};
}
// Reading a property value
if (jsonPropertySerialization.ValueSerialization is not null)
{
List<MethodBodyStatement> statements = new List<MethodBodyStatement>
{
CreatePropertyNullCheckStatement(jsonPropertySerialization, jsonProperty, propertyVariables, shouldTreatEmptyStringAsNull),
DeserializeValue(jsonPropertySerialization.ValueSerialization, jsonProperty.Value, out var value)
};
AssignValueStatement assignStatement = TypeFactory.IsReadOnlyMemory(jsonPropertySerialization.SerializedType!)
? Assign(propertyVariables[jsonPropertySerialization], New.Instance(jsonPropertySerialization.SerializedType!, value))
: Assign(propertyVariables[jsonPropertySerialization], value);
statements.Add(assignStatement);
statements.Add(Continue);
return statements;
}
// Reading a nested object
if (jsonPropertySerialization.PropertySerializations is not null)
{
return new[]
{
CreatePropertyNullCheckStatement(jsonPropertySerialization, jsonProperty, propertyVariables, shouldTreatEmptyStringAsNull),
new ForeachStatement("property", jsonProperty.Value.EnumerateObject(), out var nestedItemVariable)
{
DeserializeIntoObjectProperties(jsonPropertySerialization.PropertySerializations, new JsonPropertyExpression(nestedItemVariable), propertyVariables, shouldTreatEmptyStringAsNull)
},
Continue
};
}
throw new InvalidOperationException($"Either {nameof(JsonPropertySerialization.ValueSerialization)} must not be null or {nameof(JsonPropertySerialization.PropertySerializations)} must not be null.");
}
private static MethodBodyStatement CreatePropertyNullCheckStatement(JsonPropertySerialization jsonPropertySerialization, JsonPropertyExpression jsonProperty, IReadOnlyDictionary<JsonPropertySerialization, VariableReference> propertyVariables, bool shouldTreatEmptyStringAsNull)
{
if (jsonPropertySerialization.CustomDeserializationMethodName is not null)
{
// if we have the deserialization hook here, we do not need to do any check, all these checks should be taken care of by the hook
return EmptyStatement;
}
var checkEmptyProperty = GetCheckEmptyPropertyValueExpression(jsonProperty, jsonPropertySerialization, shouldTreatEmptyStringAsNull);
var serializedType = jsonPropertySerialization.SerializedType;
if (serializedType?.IsNullable == true)
{
// we only assign null when it is not a collection if we have DeserializeNullCollectionAsNullValue configuration is off
// specially when it is required, we assign ChangeTrackingList because for optional lists we are already doing that
if (!TypeFactory.IsCollectionType(serializedType) || Configuration.DeserializeNullCollectionAsNullValue)
{
return new IfStatement(checkEmptyProperty)
{
Assign(propertyVariables[jsonPropertySerialization], Null),
Continue
};
}
if (jsonPropertySerialization.IsRequired && !TypeFactory.IsReadOnlyMemory(serializedType))
{
return new IfStatement(checkEmptyProperty)
{
Assign(propertyVariables[jsonPropertySerialization], New.Instance(TypeFactory.GetPropertyImplementationType(serializedType))),
Continue
};
}
return new IfStatement(checkEmptyProperty)
{
Continue
};
}
// even if ReadOnlyMemory is required we leave the list empty if the payload doesn't have it
if ((!jsonPropertySerialization.IsRequired || (serializedType is not null && TypeFactory.IsReadOnlyMemory(serializedType))) &&
serializedType?.Equals(typeof(JsonElement)) != true && // JsonElement handles nulls internally
serializedType?.Equals(typeof(string)) != true) //https://github.com/Azure/autorest.csharp/issues/922
{
if (jsonPropertySerialization.PropertySerializations is null)
{
return new IfStatement(checkEmptyProperty)
{
Continue
};
}
return new IfStatement(checkEmptyProperty)
{
jsonProperty.ThrowNonNullablePropertyIsNull(),
Continue
};
}
return EmptyStatement;
}
private static BoolExpression GetCheckEmptyPropertyValueExpression(JsonPropertyExpression jsonProperty, JsonPropertySerialization jsonPropertySerialization, bool shouldTreatEmptyStringAsNull)
{
var jsonElement = jsonProperty.Value;
if (!shouldTreatEmptyStringAsNull)
{
return jsonElement.ValueKindEqualsNull();
}
if (jsonPropertySerialization.ValueSerialization is not JsonValueSerialization { Type.IsFrameworkType: true } valueSerialization)
{
return jsonElement.ValueKindEqualsNull();
}
if (!Configuration.IntrinsicTypesToTreatEmptyStringAsNull.Contains(valueSerialization.Type.FrameworkType.Name))
{
return jsonElement.ValueKindEqualsNull();
}
return Or(jsonElement.ValueKindEqualsNull(), And(jsonElement.ValueKindEqualsString(), Equal(jsonElement.GetString().Length, Int(0))));
}
/// Collects a list of properties being read from all level of object hierarchy
private static void CollectPropertiesForDeserialization(IDictionary<JsonPropertySerialization, VariableReference> propertyVariables, IEnumerable<JsonPropertySerialization> jsonProperties)
{
foreach (JsonPropertySerialization jsonProperty in jsonProperties)
{
if (jsonProperty.SerializedType is { } type)
{
var propertyDeclaration = new CodeWriterDeclaration(jsonProperty.SerializedName.ToVariableName());
if (!jsonProperty.IsRequired)
{
if (type.IsFrameworkType && type.FrameworkType == typeof(Nullable<>))
{
type = new CSharpType(type.Arguments[0].FrameworkType);
}
type = new CSharpType(Configuration.ApiTypes.OptionalPropertyType, type);
}
propertyVariables.Add(jsonProperty, new VariableReference(type, propertyDeclaration));
}
else if (jsonProperty.PropertySerializations != null)
{
CollectPropertiesForDeserialization(propertyVariables, jsonProperty.PropertySerializations);
}
}
}
public static MethodBodyStatement BuildDeserializationForMethods(JsonSerialization serialization, bool async, ValueExpression? variable, StreamExpression stream, bool isBinaryData)
{
if (isBinaryData)
{
var callFromStream = BinaryDataExpression.FromStream(stream, async);
var variableExpression = variable is not null ? new BinaryDataExpression(variable) : null;
return AssignOrReturn(variableExpression, callFromStream);
}
var declareDocument = UsingVar("document", JsonDocumentExpression.Parse(stream, async), out var document);
var deserializeValueBlock = DeserializeValue(serialization, document.RootElement, out var value);
if (!serialization.IsNullable)
{
return new[] { declareDocument, deserializeValueBlock, AssignOrReturn(variable, value) };
}
return new MethodBodyStatement[]
{
declareDocument,
new IfElseStatement
(
document.RootElement.ValueKindEqualsNull(),
AssignOrReturn(variable, Null),
new[]{deserializeValueBlock, AssignOrReturn(variable, value)}
)
};
}
public static MethodBodyStatement DeserializeValue(JsonSerialization serialization, JsonElementExpression element, out ValueExpression value)
{
switch (serialization)
{
case JsonArraySerialization jsonReadOnlyMemory when TypeFactory.IsArray(jsonReadOnlyMemory.ImplementationType):
var readOnlyMemory = new VariableReference(jsonReadOnlyMemory.ImplementationType, "array");
value = readOnlyMemory;
VariableReference index = new VariableReference(typeof(int), "index");
return new MethodBodyStatement[]
{
Declare(index, Int(0)),
Declare(readOnlyMemory, New.Array(TypeFactory.GetElementType(jsonReadOnlyMemory.ImplementationType), element.GetArrayLength())),
new ForeachStatement("item", element.EnumerateArray(), out var readOnlyMemoryItem)
{
DeserializeArrayItem(jsonReadOnlyMemory, value, new JsonElementExpression(readOnlyMemoryItem), index),
Increment(index)
}
};
case JsonArraySerialization jsonArray:
var array = new VariableReference(jsonArray.ImplementationType, "array");
value = array;
return new MethodBodyStatement[]
{
Declare(array, New.Instance(jsonArray.ImplementationType)),
new ForeachStatement("item", element.EnumerateArray(), out var arrayItem)
{
DeserializeArrayItem(jsonArray, value, new JsonElementExpression(arrayItem)),
}
};
case JsonDictionarySerialization jsonDictionary:
var deserializeDictionaryStatement = new MethodBodyStatement[]
{
Declare("dictionary", New.Dictionary(jsonDictionary.Type.Arguments[0], jsonDictionary.Type.Arguments[1]), out var dictionary),
new ForeachStatement("property", element.EnumerateObject(), out var property)
{
DeserializeDictionaryValue(jsonDictionary.ValueSerialization, dictionary, new JsonPropertyExpression(property))
}
};
value = dictionary;
return deserializeDictionaryStatement;
case JsonValueSerialization { Options: JsonSerializationOptions.UseManagedServiceIdentityV3 } valueSerialization:
var declareSerializeOptions = Var("serializeOptions", New.JsonSerializerOptions(), out var serializeOptions);
value = GetDeserializeValueExpression(element, valueSerialization.Type, valueSerialization.Format, serializeOptions);
return declareSerializeOptions;
case JsonValueSerialization valueSerialization:
value = GetDeserializeValueExpression(element, valueSerialization.Type, valueSerialization.Format);
return EmptyStatement;
default:
throw new InvalidOperationException($"{serialization.GetType()} is not supported.");
}
}
private static MethodBodyStatement DeserializeArrayItem(JsonArraySerialization serialization, ValueExpression arrayVariable, JsonElementExpression arrayItemVariable, ValueExpression? index = null)
{
bool isArray = index is not null;
List<MethodBodyStatement> statements = new List<MethodBodyStatement>();
MethodBodyStatement deserializeAndAssign = new[]
{
DeserializeValue(serialization.ValueSerialization, arrayItemVariable, out var value),
isArray ? InvokeArrayElementAssignment(arrayVariable, index!, value) : InvokeListAdd(arrayVariable, value)
};
if (CollectionItemRequiresNullCheckInSerialization(serialization.ValueSerialization))
{
statements.Add(new IfElseStatement(
arrayItemVariable.ValueKindEqualsNull(),
isArray ? InvokeArrayElementAssignment(arrayVariable, index!, Null) : InvokeListAdd(arrayVariable, Null),
deserializeAndAssign));
}
else
{
statements.Add(deserializeAndAssign);
}
return statements;
}
private static MethodBodyStatement DeserializeDictionaryValue(JsonSerialization serialization, DictionaryExpression dictionary, JsonPropertyExpression property)
{
var deserializeValueBlock = new[]
{
DeserializeValue(serialization, property.Value, out var value),
dictionary.Add(property.Name, value)
};