从 C# 类生成 JSON 模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15782982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating JSON schema from C# class
提问by Ravi Gupta
Is there any way to programmatically generate a JSON schema from a C# class?
有没有办法从 C# 类以编程方式生成 JSON 模式?
Something which we can do manually using http://www.jsonschema.net/
我们可以使用http://www.jsonschema.net/手动执行的操作
回答by Stefan Steiger
For those who land here from google searching for the reverse
(generate the C# class from JSON) - I use those fine online tools:
对于那些从谷歌搜索反向
(从 JSON 生成 C# 类)到这里的人 - 我使用这些优秀的在线工具:
JSON:
http://json2csharp.com/
(Source: http://jsonclassgenerator.codeplex.com/)
JSON:
http: //json2csharp.com/
(来源:http: //jsonclassgenerator.codeplex.com/)
XML:
http://xmltocsharp.azurewebsites.net/
(Source: https://github.com/msyoung/XmlToCSharp)
XML:
http: //xmltocsharp.azurewebsites.net/
(来源:https: //github.com/msyoung/XmlToCSharp)
回答by Rico Suter
Another option which supports generating JSON Schema v4 is NJsonSchema:
另一个支持生成 JSON Schema v4 的选项是NJsonSchema:
var schema = JsonSchema4.FromType<Person>();
var schemaJson = schema.ToJson();
The library can be installed via NuGet.
该库可以通过NuGet安装。
Update for NJsonSchema v9.4.3+:
NJsonSchema v9.4.3+ 的更新:
using NJsonSchema;
var schema = await JsonSchema4.FromTypeAsync<Person>();
var schemaJson = schema.ToJson();
回答by Daniel
JsonSchemaGenerator js = new JsonSchemaGenerator();
var schema = js.Generate(typeof(Person));
schema.Title = typeof(Person).Name;
using (StreamWriter fileWriter = File.CreateText(filePath))
{
fileWriter.WriteLine(schema);
}