2

I am evaluating Json.Net.Schema from NewtonSoft and NJsonSchema from GitHub and I cannot figure out how to create a JSON schema from a JSON object. I want it to work exactly like this site does: http://jsonschema.net/#/

What I am looking for

string json = @"{""Name"": ""Bill"",""Age"": 51,""IsTall"": true}";

var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);

I would expect a valid JSON schema in the jsonSchemaRepresentation variable. Does anyone know how I can accomplish this?

Thanks in advance!

dbc
  • 104,963
  • 20
  • 228
  • 340
Jerrod Horton
  • 1,605
  • 1
  • 15
  • 30

3 Answers3

4

The current version of NJsonSchema supports this feature:

The SampleJsonSchemaGenerator generates a JSON Schema from sample JSON data.

var schema = JsonSchema4.FromSampleJson("...");
var schemaJson = schema.ToJson();

... or create a SampleJsonSchemaGenerator instance and call the Generate("...") method.

Community
  • 1
  • 1
Rico Suter
  • 11,548
  • 6
  • 67
  • 93
  • Please don't just post some tool or library as an answer. At least demonstrate [how it solves the problem](http://meta.stackoverflow.com/a/251605) in the answer itself. – Blue Nov 08 '18 at 20:45
1

Actually both of the libraries you mentioned do not support such a functionality.

If you're down to implement it yourself then you will have to parse your JSON, iterate over it recursively and add a new schema depending on the type of what you've just iterated over.

There are also some other tools (in other languages like python) which could be an inspiration, this might get you started.

Phonolog
  • 6,321
  • 3
  • 36
  • 64
  • 1
    Not correct, the current version of NJsonSchema supports this scenario: https://github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator – Rico Suter Nov 05 '18 at 20:34
0

The string you are submitting to the function is not in the correct format. Try this (add '{' to the start of the string, '}' to the end):

string json = @"{
""Name"": ""Bill"",
""Age"": 51,
""IsTall"": true
}";

var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);
B. Leduc
  • 18
  • 4
  • Sorry, I misentered my string. I have the correct string, thanks for posting this. I have a valid json string and need a valid json schema from it. – Jerrod Horton Aug 27 '16 at 19:46