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!

4
  • What schema do you end up with in jsonSchemaRepresentation (i.e. what's wrong with it?) Commented Aug 27, 2016 at 20:50
  • The method is a made up method. I need to create a method that turns the json into its corresponding json schema. Commented Aug 28, 2016 at 13:13
  • Did you find a solution to this? Commented May 18, 2017 at 14:18
  • I did not find a solution Commented May 18, 2017 at 17:19

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Please don't just post some tool or library as an answer. At least demonstrate how it solves the problem in the answer itself.
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.

1 Comment

Not correct, the current version of NJsonSchema supports this scenario: github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator
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);

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.