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:

  1. // Only this property is serialized as string
  2. [JsonConverter(typeof(StringEnumConverter))]
  3. public Gender Gender { get; set; }
  4.  
  5. // Always serialized as string
  6. [JsonConverter(typeof(StringEnumConverter))]
  7. public enum Gender
  8. {
  9. ...
  10. }

Also see Enums

https://stackoverflow.com/questions/36452468/swagger-ui-web-api-documentation-present-enums-as-strings

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.

  1. GlobalConfiguration.Configuration
  2. .EnableSwagger(c =>
  3. {
  4. c.DocumentFilter<SwaggerAddEnumDescriptions>();
  5.  
  6. //disable this
  7. //c.DescribeAllEnumsAsStrings()

SwaggerAddEnumDescriptions.cs:

  1. using System;
  2. using System.Web.Http.Description;
  3. using Swashbuckle.Swagger;
  4. using System.Collections.Generic;
  5.  
  6. public class SwaggerAddEnumDescriptions : IDocumentFilter
  7. {
  8. public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
  9. {
  10. // add enum descriptions to result models
  11. foreach (KeyValuePair<string, Schema> schemaDictionaryItem in swaggerDoc.definitions)
  12. {
  13. Schema schema = schemaDictionaryItem.Value;
  14. foreach (KeyValuePair<string, Schema> propertyDictionaryItem in schema.properties)
  15. {
  16. Schema property = propertyDictionaryItem.Value;
  17. IList<object> propertyEnums = property.@enum;
  18. if (propertyEnums != null && propertyEnums.Count > )
  19. {
  20. property.description += DescribeEnum(propertyEnums);
  21. }
  22. }
  23. }
  24.  
  25. // add enum descriptions to input parameters
  26. if (swaggerDoc.paths.Count > )
  27. {
  28. foreach (PathItem pathItem in swaggerDoc.paths.Values)
  29. {
  30. DescribeEnumParameters(pathItem.parameters);
  31.  
  32. // head, patch, options, delete left out
  33. List<Operation> possibleParameterisedOperations = new List<Operation> { pathItem.get, pathItem.post, pathItem.put };
  34. possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.parameters));
  35. }
  36. }
  37. }
  38.  
  39. private void DescribeEnumParameters(IList<Parameter> parameters)
  40. {
  41. if (parameters != null)
  42. {
  43. foreach (Parameter param in parameters)
  44. {
  45. IList<object> paramEnums = param.@enum;
  46. if (paramEnums != null && paramEnums.Count > )
  47. {
  48. param.description += DescribeEnum(paramEnums);
  49. }
  50. }
  51. }
  52. }
  53.  
  54. private string DescribeEnum(IList<object> enums)
  55. {
  56. List<string> enumDescriptions = new List<string>();
  57. foreach (object enumOption in enums)
  58. {
  59. enumDescriptions.Add(string.Format("{0} = {1}", (int)enumOption, Enum.GetName(enumOption.GetType(), enumOption)));
  60. }
  61. return string.Join(", ", enumDescriptions.ToArray());
  62. }
  63.  
  64. }

This results in something like the following on your swagger-ui so at least you can "see what you're doing":

NSwag enum的更多相关文章

  1. NSwag生成客户端调用代码

    NetCore2.1 WebAPI 根据swagger.json自动生成客户端代码 https://www.cnblogs.com/hunanzp/p/9297361.html 前言 上一篇博客中我们 ...

  2. .net core的Swagger接口文档使用教程(二):NSwag

    上一篇介绍了Swashbuckle ,地址:.net core的Swagger接口文档使用教程(一):Swashbuckle 讲的东西还挺多,怎奈微软还推荐了一个NSwag,那就继续写吧! 但是和Sw ...

  3. Swift enum(枚举)使用范例

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  4. 枚举:enum

    枚举 所谓枚举就是指定好取值范围,所有内容只能从指定范围取得. 例如,想定义一个color类,他只能有RED,GREEN,BLUE三种植. 使用简单类完成颜色固定取值问题. 1,就是说,一个类只能完成 ...

  5. Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件

    在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...

  6. 用枚举enum替代int常量

    枚举的好处: 1. 类型安全性 2.使用方便性 public class EnumDemo { enum Color{ RED(3),BLUE(5),BLACK(8),YELLOW(13),GREEN ...

  7. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  8. c# (ENUM)枚举组合类型的谷歌序列化Protobuf

    c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...

  9. (转)C# Enum,Int,String的互相转换 枚举转换

    Enum为枚举提供基类,其基础类型可以是除 Char 外的任何整型.如果没有显式声明基础类型,则使用 Int32.编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举. 注意:枚举类型的基 ...

随机推荐

  1. [python+opencv] ROI(Range Of Interest)与泛洪填充

    python+opencv3.3视频教学 基础入门笔记(贾志刚老师) https://www.bilibili.com/video/av24998616/?p=8 ROI(Range Of Inter ...

  2. mysql清空有外键关联的表

    第一种:(不要外键约束) 手动删除外键约束: 删除表数据 第二种:(保留外键约束) SET FOREIGN_KEY_CHECKS = 0;   TRUNCATE TABLE 表名;  SET FORE ...

  3. (2.17)Mysql之SQL基础——日期函数

    关键词:mysql时间函数,mysql日期函数 [1]curdate():返回当前日期(2019-03-06),curdate()+0 返回(20190306) [2]curtime():返回当前时间 ...

  4. ajax请求session失效重定向到登录页面

    在ajax请求的页面引入一个自定义的AjaxRedirect.js的文件 AjaxRedirect.js的代码如下: $(function(){ $.ajaxSetup({ type: 'POST', ...

  5. Java多线程的下载器(1)

    实现了一个基于Java多线程的下载器,可提供的功能有: 1. 对文件使用多线程下载,并显示每时刻的下载速度. 2. 对多个下载进行管理,包括线程调度,内存管理等. 一:单个文件下载的管理 1. 单文件 ...

  6. svg绘图工具raphael.js的使用

    1.raphael.js svg画图的开源库,支持IE8+ 官方api: http://dmitrybaranovskiy.github.io/raphael/reference.html Githu ...

  7. VMware coding Challenge

    思路:这道题要观察,举个例子,1 2 * * 3 * 4  5 * * 6 7 * 8 * *, 用Stack,先序遍历,遇到数字就入栈,如果遇到 * *,说明栈顶节点是叶子节点,一条根到叶子的路径这 ...

  8. 如何在SQL Server查询语句(Select)中检索存储过程(Store Procedure)的结果集?

    如何在SQL Server查询语句(Select)中检索存储过程(Store Procedure)的结果集?(2006-12-14 09:25:36) 与这个问题具有相同性质的其他描述还包括:如何 ...

  9. acrobat pro 无法编辑个别文本

    在修改pdf文档时出现个别文字选取不上,无法修改,如图中4-2626没有选中 解决方法如图 此后可以直接修改文本了

  10. vue数据双向绑定原理

    vue的数据双向绑定的小例子: .html <!DOCTYPE html> <html> <head> <meta charset=utf-> < ...