11using System ;
2- using Microsoft . OpenApi . Models ;
2+ using Microsoft . OpenApi ;
33using Swashbuckle . AspNetCore . SwaggerGen ;
44using System . Collections ;
55using System . Collections . Generic ;
6- using System . Reflection ;
7- using Microsoft . OpenApi . Any ;
6+ using System . Text . Json . Nodes ;
87
98namespace SimApi . SwaggerFilters ;
109
1110public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
1211{
13- public void Apply ( OpenApiSchema schema , SchemaFilterContext context )
12+ public void Apply ( IOpenApiSchema schema , SchemaFilterContext context )
1413 {
1514 if ( ! IsDynamicObjectType ( context . Type ) ) return ;
16- schema . AdditionalPropertiesAllowed = true ;
17- schema . AdditionalProperties = new OpenApiSchema
15+ var oaSchema = schema as OpenApiSchema ;
16+ oaSchema . AdditionalPropertiesAllowed = true ;
17+ oaSchema . AdditionalProperties = new OpenApiSchema
1818 {
19- Type = "object" , // 表示 value 可以是任意类型(兼容所有类型)
20- Nullable = true
19+ Type = JsonSchemaType . Object , // 表示 value 可以是任意类型(兼容所有类型)
2120 } ;
2221
2322 // 2. 覆盖默认示例,使用包含多种类型的示例
24- schema . Example = CreateMultiTypeExample ( ) ;
23+ oaSchema . Example = CreateMultiTypeExample ( ) ;
2524 }
2625
2726 // 判断是否为需要处理的“动态对象”类型
@@ -33,30 +32,39 @@ private bool IsDynamicObjectType(Type? type)
3332 {
3433 return true ;
3534 }
35+
3636 if ( type == typeof ( object ) )
3737 {
3838 return true ;
3939 }
40+
4041 return type . Name . Contains ( "AnonymousType" ) && type . Namespace == null ;
4142 }
4243
4344 // 创建包含多种类型的示例(覆盖默认的 string 示例)
44- private OpenApiObject CreateMultiTypeExample ( )
45+ private JsonNode CreateMultiTypeExample ( )
4546 {
46- return new OpenApiObject
47+ return new JsonObject
4748 {
48- [ "stringProp" ] = new OpenApiString ( "example string" ) , // 字符串
49- [ "numberProp" ] = new OpenApiInteger ( 123 ) , // 数字
50- [ "boolProp" ] = new OpenApiBoolean ( true ) , // 布尔值
51- [ "objectProp" ] = new OpenApiObject // 嵌套对象
49+ // 字符串类型:JsonValue.Create 包装字符串
50+ [ "stringProp" ] = JsonValue . Create ( "example string" ) ,
51+ // 数字类型:支持 int/long/double 等,JsonValue 自动适配
52+ [ "numberProp" ] = JsonValue . Create ( 123 ) ,
53+ // 布尔类型
54+ [ "boolProp" ] = JsonValue . Create ( true ) ,
55+ // 嵌套对象:JsonObject 对应 OpenApiObject
56+ [ "objectProp" ] = new JsonObject
5257 {
53- [ "nestedKey" ] = new OpenApiString ( "nested value" )
58+ [ "nestedKey" ] = JsonValue . Create ( "nested value" )
5459 } ,
55- [ "arrayProp" ] = new OpenApiArray // 数组
60+ // 数组类型:JsonArray 对应 OpenApiArray
61+ [ "arrayProp" ] = new JsonArray
5662 {
57- new OpenApiInteger ( 1 ) ,
58- new OpenApiString ( "two" )
59- }
63+ JsonValue . Create ( 1 ) , // 数组内数字
64+ JsonValue . Create ( "two" ) // 数组内字符串
65+ } ,
66+ // 可选:添加 null 值示例(若需要)
67+ [ "nullProp" ] = null
6068 } ;
6169 }
6270}
0 commit comments