@@ -68,17 +68,24 @@ public static Request Build(IControllerMetaData metaData, KeyValuePair<HttpMetho
6868 return body ;
6969 }
7070
71- private static string BuildRequestJsonData ( Type modelType ) => JsonSerializer . Serialize ( CreateObject ( modelType ) , new JsonSerializerOptions
71+ private static string BuildRequestJsonData ( Type modelType )
7272 {
73- WriteIndented = true
74- } ) ;
73+ var model = CreateObject ( modelType ) ;
7574
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 )
7784 {
7885 if ( IsGenericList ( modelType ) )
7986 modelType = ConstructGenericListTypeFromGenericIList ( modelType ) ;
8087
81- return Activator . CreateInstance ( modelType ) ;
88+ return Activator . CreateInstance ( modelType ) ?? throw new InvalidOperationException ( "Error creating model." ) ;
8289 }
8390
8491 private static bool IsGenericList ( Type type ) => type . IsGenericType && typeof ( IList < > ) . IsAssignableFrom ( type . GetGenericTypeDefinition ( ) ) ;
@@ -91,4 +98,25 @@ private static Type ConstructGenericListTypeFromGenericIList(Type sourceListType
9198
9299 return type . MakeGenericType ( typeArgs ) ;
93100 }
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+ }
94122}
0 commit comments