Jerrod Horton
Jerrod Horton

Reputation: 1692

How to create json schema from json object string C#

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!

Upvotes: 2

Views: 9114

Answers (3)

Rico Suter
Rico Suter

Reputation: 11858

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.

Upvotes: 4

Phonolog
Phonolog

Reputation: 6511

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.

Upvotes: 1

B. Leduc
B. Leduc

Reputation: 58

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

Upvotes: 0

Related Questions