NSwag enum
https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaGenerator#integer-vs-string-enumerations
Integer vs string enumerations
JSON Schema supports integer and string enumerations. In Json.NET, enums are serialized as integer by default. However you can mark a property with the JsonConverterAttribute
so that it is serialized as string. NJsonSchema looks for these attributes and generates the enum JSON Schema respecting this attribute:
// Only this property is serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public Gender Gender { get; set; } // Always serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public enum Gender
{
...
}
Also see Enums
So I think I have a similar problem. I'm looking for swagger to generate enums along with the int -> string mapping. The API must accept the int. The swagger-ui matters less, what I really want is code generation with a "real" enum on the other side (android apps using retrofit in this case).
So from my research this ultimately seems to be a limit of the OpenAPI specification which Swagger uses. It's not possible to specify names and numbers for enums.
The best issue I've found to follow is https://github.com/OAI/OpenAPI-Specification/issues/681 which looks like a "maybe soon" but then Swagger would have to be updated, and in my case Swashbuckle as well.
For now my workaround has been to implement a document filter that looks for enums and populates the relevant description with the contents of the enum.
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.DocumentFilter<SwaggerAddEnumDescriptions>(); //disable this
//c.DescribeAllEnumsAsStrings()
SwaggerAddEnumDescriptions.cs:
using System;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
using System.Collections.Generic; public class SwaggerAddEnumDescriptions : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
// add enum descriptions to result models
foreach (KeyValuePair<string, Schema> schemaDictionaryItem in swaggerDoc.definitions)
{
Schema schema = schemaDictionaryItem.Value;
foreach (KeyValuePair<string, Schema> propertyDictionaryItem in schema.properties)
{
Schema property = propertyDictionaryItem.Value;
IList<object> propertyEnums = property.@enum;
if (propertyEnums != null && propertyEnums.Count > )
{
property.description += DescribeEnum(propertyEnums);
}
}
} // add enum descriptions to input parameters
if (swaggerDoc.paths.Count > )
{
foreach (PathItem pathItem in swaggerDoc.paths.Values)
{
DescribeEnumParameters(pathItem.parameters); // head, patch, options, delete left out
List<Operation> possibleParameterisedOperations = new List<Operation> { pathItem.get, pathItem.post, pathItem.put };
possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.parameters));
}
}
} private void DescribeEnumParameters(IList<Parameter> parameters)
{
if (parameters != null)
{
foreach (Parameter param in parameters)
{
IList<object> paramEnums = param.@enum;
if (paramEnums != null && paramEnums.Count > )
{
param.description += DescribeEnum(paramEnums);
}
}
}
} private string DescribeEnum(IList<object> enums)
{
List<string> enumDescriptions = new List<string>();
foreach (object enumOption in enums)
{
enumDescriptions.Add(string.Format("{0} = {1}", (int)enumOption, Enum.GetName(enumOption.GetType(), enumOption)));
}
return string.Join(", ", enumDescriptions.ToArray());
} }
This results in something like the following on your swagger-ui so at least you can "see what you're doing":
NSwag enum的更多相关文章
- NSwag生成客户端调用代码
NetCore2.1 WebAPI 根据swagger.json自动生成客户端代码 https://www.cnblogs.com/hunanzp/p/9297361.html 前言 上一篇博客中我们 ...
- .net core的Swagger接口文档使用教程(二):NSwag
上一篇介绍了Swashbuckle ,地址:.net core的Swagger接口文档使用教程(一):Swashbuckle 讲的东西还挺多,怎奈微软还推荐了一个NSwag,那就继续写吧! 但是和Sw ...
- Swift enum(枚举)使用范例
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...
- 枚举:enum
枚举 所谓枚举就是指定好取值范围,所有内容只能从指定范围取得. 例如,想定义一个color类,他只能有RED,GREEN,BLUE三种植. 使用简单类完成颜色固定取值问题. 1,就是说,一个类只能完成 ...
- Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件
在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...
- 用枚举enum替代int常量
枚举的好处: 1. 类型安全性 2.使用方便性 public class EnumDemo { enum Color{ RED(3),BLUE(5),BLACK(8),YELLOW(13),GREEN ...
- The Java Enum: A Singleton Pattern [reproduced]
The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...
- c# (ENUM)枚举组合类型的谷歌序列化Protobuf
c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...
- (转)C# Enum,Int,String的互相转换 枚举转换
Enum为枚举提供基类,其基础类型可以是除 Char 外的任何整型.如果没有显式声明基础类型,则使用 Int32.编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举. 注意:枚举类型的基 ...
随机推荐
- paas容器云
- java执行Shell命令
java程序中要执行linux命令主要依赖2个类:Process和Runtime首先看一下Process类:ProcessBuilder.start() 和 Runtime.exec 方法创建一个本机 ...
- 居然上了模板使用排行榜第一 happy一下
这段时间在学习css和div,顺便把博客给整了一下,然后不小心就上了FFandIE模板使用排行榜第一,happy一下下.不知道这个算不算排名,还是随机刷新.感觉应该是按流量统计的,这段时间有几篇文章一 ...
- 【Espruino】NO.07 获取电压值
http://blog.csdn.net/qwert1213131/article/details/27985645 本文属于个人理解,能力有限,纰漏在所难免.还望指正! [小鱼有点电] 前几节的内容 ...
- 001-nginx基础配置-location
一.基础语法 Location block 的基本语法形式是: location [=|~|~*|^~|@] pattern { ... } [=|~|~*|^~|@] 被称作 location mo ...
- Spark2.x学习笔记:Spark SQL快速入门
Spark SQL快速入门 本地表 (1)准备数据 [root@node1 ~]# mkdir /tmp/data [root@node1 ~]# cat data/ml-1m/users.dat | ...
- [py]python面向对象的str getattr特殊方法
本文旨在说清楚 类中的 def init def str def getattr 这三个方法怎么用的. 定制输入实例名时输出内容 def __str__会定制输出实例名时候的输出 class Chai ...
- SQL Server 公用表表达式(CTE)实现递归的方法
公用表表达式简介: 公用表表达式 (CTE) 可以认为是在单个 SELECT.INSERT.UPDATE.DELETE 或 CREATE VIEW 语句的执行范围内定义的临时结果集.CTE 与派生表类 ...
- 将Pytorch模型从CPU转换成GPU
1. 如何进行迁移 对模型和相应的数据进行.cuda()处理.通过这种方式,我们就可以将内存中的数据复制到GPU的显存中去.从而可以通过GPU来进行运算了. 1.1 判定使用GPU 下载了对应的GPU ...
- Repeater 控件使用总结
关于Repeater控件使用的一些总结,希望能对将来有机会看到这篇日志的同事有所帮助.也是为了在自己开发有所遗忘的时候能够参考一下.前言:Repeater是一个迭代控件,什么是迭代控件呢?书本上的 ...