@@ -68,17 +68,24 @@ public static Request Build(IControllerMetaData metaData, KeyValuePair<HttpMetho
68
68
return body ;
69
69
}
70
70
71
- private static string BuildRequestJsonData ( Type modelType ) => JsonSerializer . Serialize ( CreateObject ( modelType ) , new JsonSerializerOptions
71
+ private static string BuildRequestJsonData ( Type modelType )
72
72
{
73
- WriteIndented = true
74
- } ) ;
73
+ var model = CreateObject ( modelType ) ;
75
74
76
- private static object ? CreateObject ( Type modelType )
75
+ InitializeListsSingleEmptyValues ( model ) ;
76
+
77
+ return JsonSerializer . Serialize ( model , new JsonSerializerOptions
78
+ {
79
+ WriteIndented = true
80
+ } ) ;
81
+ }
82
+
83
+ private static object CreateObject ( Type modelType )
77
84
{
78
85
if ( IsGenericList ( modelType ) )
79
86
modelType = ConstructGenericListTypeFromGenericIList ( modelType ) ;
80
87
81
- return Activator . CreateInstance ( modelType ) ;
88
+ return Activator . CreateInstance ( modelType ) ?? throw new InvalidOperationException ( "Error creating model." ) ;
82
89
}
83
90
84
91
private static bool IsGenericList ( Type type ) => type . IsGenericType && typeof ( IList < > ) . IsAssignableFrom ( type . GetGenericTypeDefinition ( ) ) ;
@@ -91,4 +98,25 @@ private static Type ConstructGenericListTypeFromGenericIList(Type sourceListType
91
98
92
99
return type . MakeGenericType ( typeArgs ) ;
93
100
}
101
+
102
+ private static void InitializeListsSingleEmptyValues ( object model )
103
+ {
104
+ var type = model . GetType ( ) ;
105
+
106
+ foreach ( var propertyInfo in type . GetProperties ( ) )
107
+ {
108
+ if ( ! IsGenericList ( propertyInfo . PropertyType ) )
109
+ continue ;
110
+
111
+ var listObjectType = propertyInfo . PropertyType . GetGenericArguments ( ) [ 0 ] ;
112
+ var emptyListType = ConstructGenericListTypeFromGenericIList ( propertyInfo . PropertyType ) ;
113
+
114
+ var emptyList = Activator . CreateInstance ( emptyListType ) ;
115
+ var emptyItem = Activator . CreateInstance ( listObjectType ) ;
116
+
117
+ emptyListType . GetMethod ( "Add" ) ! . Invoke ( emptyList , new [ ] { emptyItem } ) ;
118
+
119
+ propertyInfo . SetValue ( model , emptyList ) ;
120
+ }
121
+ }
94
122
}
0 commit comments