如何从 json 对象字符串 C# 创建 json 模式

How to create json schema from json object string C#

我正在评估 NewtonSoft 的 Json.Net.Schema 和 GitHub 的 NJsonSchema,但我不知道如何从 JSON 对象创建 JSON 模式。我希望它像这个网站一样工作:http://jsonschema.net/#/

我在找什么

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

var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);

我希望 jsonSchemaRepresentation 变量中有一个有效的 JSON 模式。有谁知道我怎样才能做到这一点?

提前致谢!

您提交给函数的字符串格式不正确。试试这个(将“{”添加到字符串的开头,将“}”添加到末尾):

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

var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);

实际上你提到的两个库都不支持这样的功能

如果您决定自己实施它,那么您将不得不根据您刚刚迭代的内容的类型来解析您的 JSON、iterate over it recursively and add a new schema

还有一些其他工具(使用其他语言,如 python)可能会有所启发,this 可能会让您入门。

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.