84

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.

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 :

  • To generate C# classes from a JSON Schema.
  • To convert a JSON Schema to an XSD file. Then it would be easy to create the classes as there are plenty of tool to generate classes from XSD.

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.

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).

Julien N
  • 3,880
  • 4
  • 28
  • 46
  • 2
    This question is not exactly what I'm looking for. I don't have any JSON string, I just have a JSON Schema. There are tools for JSON string -> Class. But can't find one for JSON Schema -> Class. – Julien N Jun 15 '11 at 13:58
  • 2
    I found this site, it's perfect for converting JSON Schemas to C#, enums, JsonConverters and all: https://quicktype.io/csharp/ . (Can't leave an answer as the question has been closed. It's a good question but there have been no complete answers.) – Matt D May 22 '20 at 16:40
  • Thank you @MattD finally someone posted the right answer – vander Apr 24 '21 at 05:56

8 Answers8

59

Visual Studio 2017 has this feature.

From the menu, choose Edit, Paste Special, Paste JSON As Classes. Paste in the JSON and Visual Studio will create the required classes.

enter image description here

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
SDAL
  • 670
  • 5
  • 7
  • 2
    Thanks, its worked great for me, you saved my a lot of time :) – khawarPK Apr 30 '18 at 06:50
  • 54
    Doesn't work for a SCHEMA ... Just a JSON string – Chris Hammond Sep 20 '18 at 11:27
  • I has issues with JSON2CSHARP, but this answer worked perfectly – user3580480 Sep 25 '19 at 17:25
  • 3
    up voted for useful info. Yet, would be better to use schema since they specify optional/required properties, default values, etc. Those details are lost when generating the classes from data. So you could end up with something that is structurally correct, but that doesn't actually meet a required spec. – Yogi Oct 11 '19 at 17:40
  • 1
    This might not be from a schema but it was exacly what i was looking for! thanks man! – lsp Apr 22 '20 at 10:26
  • Has to be from Schema, "sample" files are unlikely to have all of the possible permutations. So disappointed that Visual Studio (or Code) have not provided this. – David V. Corbin Aug 11 '21 at 15:51
  • I dont see this in VS 2022 – Ted Jan 02 '23 at 15:55
48

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();

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

Rohit L
  • 1,441
  • 13
  • 12
  • 3
    @rico-suter No one has ever explained properly how to load all reference schemas residing in a folder while generating code. Not a single example on any site till today. – Sukhdevsinh Zala Jun 30 '20 at 11:00
  • 2
    This is now a correct URL to json2csharp converter tool https://json2csharp.com. – Egel Nov 04 '20 at 09:10
  • 3
    will also point out that you actually need to add at least two packages to make this work... NJsonSchema.CodeGeneration (which adds other pkgs like NJsonSchema) AND NJsonSchema.CodeGeneration.CSharp. – josh Dec 12 '20 at 08:13
  • 1
    The site doesn't translate json schema any more. Just json data. :-( – m12lrpv Mar 09 '21 at 02:13
  • but does not support "onOf" a common Schema element... – David V. Corbin Aug 12 '21 at 10:54
8

You can use the library NJsonSchema to read a JSON schema or generate one from a type, and generate a C# class from it.

If you need a GUI for these tasks, you can try the NSwagStudio GUI from the NSwag tools to do so... (it is also based on NJsonSchema)

Rico Suter
  • 11,548
  • 6
  • 67
  • 93
7

In order to answer this correctly you need to know what version (draft) the Json Schema has.

Examples which libraries can handle which Schema (2018-01-19):

Json.NET Schema supports draft 3, draft 4, draft 6 (MIT)
Manatee.Json supports draft 4, draft 6, draft 7 (MIT)
NJsonSchema supports draft 4 (Ms-PL)

http://json-schema.org/implementations.html#validator-dotnet

With NJsonSchema.CodeGeneration you can't send the actual JSON in directly either, you first need to convert it to an actual schema (You will often get the error: Unable to cast object of type 'System.String' to type 'NJsonSchema.JsonSchema4 otherwise).

Example with running code, Schemas folder located at project root:

class Program
{
    static void Main(string[] args)
    {
        var location = Assembly.GetExecutingAssembly().Location;
        var path = Path.GetFullPath(Path.Combine(location, @"..\..\..\Schemas"));
        var schemaJson = File.ReadAllText($"{path}Test.json");
        var schema = JsonSchema4.FromJsonAsync(schemaJson).Result;
        var generator = new CSharpGenerator(schema);
        var generatedFile = generator.GenerateFile();
    }
}
Lemonseed
  • 1,644
  • 1
  • 15
  • 29
Ogglas
  • 62,132
  • 37
  • 328
  • 418
5

So I'm looking for a tool that would allow me either : To generate C# classes from a JSON Schema...

I haven't used it myself so I can't comment too much about it, but it seems like the tool "json-schema-to-poco" would fit what you need.

Per its github readme:

Converts JSON schema files into plain old CLR objects in C#. Useful for running as part of an automated build process.

Tim Cooke
  • 119
  • 1
  • 5
4

Here is an online class generator that I've used in the past to generate C# classes from a sample set of JSON data:

http://json2csharp.com/

Bill Sambrone
  • 4,334
  • 4
  • 48
  • 70
4

I had a need for this today and didn't see any solid answers to your question so I whipped this up. It's not perfect but it's a good starting point to build off of.

https://gist.github.com/rushfrisby/c8f58f346548bf31e045

Rush Frisby
  • 11,388
  • 19
  • 63
  • 83
  • 1
    Nice one, yours is the first schema to code generator, and not example json to code gen I have found that actually works. – Vdex Oct 14 '14 at 11:00
  • 1
    I have blatantly ripped off @rushonroeks code and split it out so i can gen other code/models - specifically Knockout view models : https://gist.github.com/RhysC/480e7a758639a3215701 – RhysC Oct 31 '14 at 02:56
  • Note that rushonerok's code relies on JSON.NET which hasn't yet been updated to support JsonSchema v4: https://github.com/JamesNK/Newtonsoft.Json/issues/115 – cbp Feb 24 '15 at 05:48
  • if you're interest in adapting this code for v4 JNK wrote a library for it which can be found at https://www.nuget.org/packages/Newtonsoft.Json.Schema – Rush Frisby Feb 24 '15 at 13:46
  • Doesn't work for me. I have a simple Json schema and it cannot translate it. I have not had such an issue with NJsonSchema. My schema: https://file.io/YQKnrB8gfgxa – Artexias Feb 12 '22 at 08:52
-1

Have a look at the Help of Json.NET There is a Json.Schema namespace that can be useful.

http://james.newtonking.com/projects/json/help/

Json.NET - Quick Starts & API Documentation Newtonsoft.Json.Schema Namespace Namespaces ► Newtonsoft.Json.Schema

The project page: http://json.codeplex.com/

Carlos Quintanilla
  • 12,937
  • 3
  • 22
  • 25
  • 1
    Yeah, I've seen that, but aside from building my own class generator (which I'll probably do if I don't find an existing tool), I don't think it can help me to generate those classes without too much effort. – Julien N Jun 15 '11 at 15:52
  • @JulienN did you ever write your own class generator? – Ryan Davis May 21 '14 at 16:47
  • Sorry I don't remember but I don't think so, I probably didn't have the time, I would have published it if I did :). 3 years later, it still doesn't exist ? – Julien N May 21 '14 at 16:59
  • @JulienN if it does exist, this question ranks higher on google. I'll keep searching, thanks for the quick reply. – Ryan Davis May 21 '14 at 17:28
  • Did anyone found any solution to this ? In my case even similar thing in JavaScript would do the job ? – khorvat Jul 04 '14 at 10:15