从JSON模式生成C#类 [英] Generate C# classes from JSON Schema

查看:85
本文介绍了从JSON模式生成C#类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个C#WCF Web服务,该服务以JSON格式返回很多数据. 该客户端是一个iPad应用程序,当前正在由另一个团队开发,因此我正在研究规范,而没有示例数据.
当前JSON字符串是由.net框架创建的,我的Web服务正在返回一个C#对象,该对象包含所有信息,然后由框架使用DataContracts对其进行序列化.

I'm creating a C# WCF Web Service that return a lot of data in a JSON format. The client is an iPad application that is currently being developped by another team, So I'm working on specifications, without example data.
Currently the JSON string is created by the .net framework, my Web Service is returning a C# object containing all the information that are then serialized by the framework using DataContracts.

我的问题是通信规范仅包含JSON模式文件(基于 http://json-schema.org/) .为了促进开发,我想在C#中生成相应的类,但是由于文件包含大量信息并且有十几个文件,所以我真的不想手动创建这些类.

My problem is that the communication specifications only contain JSON Schema files (based on http://json-schema.org/). In order to facilitate the development I'd like to generate the corresponding classes in C# but as the files contain quite a lot of information and there are a dozen of files, I don't really want to create those classes manually.

所以我正在寻找一种允许我使用的工具:

So I'm looking for a tool that would allow me either :

  • 要从JSON模式生成C#类.
  • 要将JSON模式转换为XSD文件.这样一来,创建类就很容易了,因为有很多工具可以从XSD生成类.

我找到了很多工具来根据JSON Schema验证JSON字符串或从JSON字符串生成类,但是似乎没有任何帮助.
有一个 JSON.NET ,但它似乎是一个库而不是一个工具,我没有找到有关使用它生成类的任何信息.

I found a lot of tools to validate a JSON string against a JSON Schema or to generate classes from the JSON string but nothing that seem to help me.
There is JSON.NET but it seems to be a library and not a tool and I didn't found any information about generating classes with it.

因此,如果有人知道工具或对如何生成这些类有想法(我尝试过使用Java创建类的工具,但我无法使其工作).

So if anyone knows a tools or has an idea on how I could generate those classes (I tried a tool that create the classes in Java but I couldn't make it work).

推荐答案

在nuget上查找此库. NJsonSchema.CodeGeneration 可用于从JSON模式生成C#或TypeScript代码:

Look up this library on nuget. The NJsonSchema.CodeGeneration can be used to generate C# or TypeScript code from a JSON schema:

var generator = new CSharpGenerator(schema);
var file = generator.GenerateFile();

文件变量现在包含JSON模式中定义的所有类的C#代码.

The file variable now contains the C# code for all the classes defined in the JSON schema.

我需要一个今天生成的类,但找不到任何可以在线将json模式转换为c#类的站点,因此使用了上述库并快速编写了一些内容

I needed a class generated today but couldn't find any site that could convert json schema to c# classes online so used the above mentioned library and wrote something up quickly http://json2csharp.rohitl.com/ hope this helps.

这篇关于从JSON模式生成C#类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆