json:
{'name': 'John Doe','age': 30,'isEmployee': true,'address': {'street': '123 Main St','city': 'Anytown','state': 'CA'},'hobbies': ['reading', 'gaming', 'sports']}
program:
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using System;class Program
{static void Main(){string jsonString = @"{'name': 'John Doe','age': 30,'isEmployee': true,'address': {'street': '123 Main St','city': 'Anytown','state': 'CA'},'hobbies': ['reading', 'gaming', 'sports']}";JToken jsonToken = JToken.Parse(jsonString);JSchema schema = GenerateSchema(jsonToken);string schemaJson = schema.ToString();Console.WriteLine(schemaJson);}static JSchema GenerateSchema(JToken token){JSchema schema = new JSchema();switch (token.Type){case JTokenType.Object:schema.Type = JSchemaType.Object;var requiredProperties = new List<string>();foreach (var property in token.Children<JProperty>()){var propertySchema = GenerateSchema(property.Value);schema.Properties[property.Name] = propertySchema;if (property.Value.Type != JTokenType.Null) // 假设非null属性是必需的{schema.Required.Add(property.Name);}}break;case JTokenType.Array:schema.Type = JSchemaType.Array;foreach (var item in token){var itemSchema = GenerateSchema(item);schema.Items.Add(itemSchema);}break;case JTokenType.String:schema.Type = JSchemaType.String;break;case JTokenType.Integer:schema.Type = JSchemaType.Integer;break;case JTokenType.Float:schema.Type = JSchemaType.Number;break;case JTokenType.Boolean:schema.Type = JSchemaType.Boolean;break;case JTokenType.Null:schema.Type = JSchemaType.Null;break;default:schema.Type = JSchemaType.Object;break;}return schema;}
}
output:
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
},
"isEmployee": {
"type": "boolean"
},
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
}
},
"required": [
"street",
"city",
"state"
]
},
"hobbies": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"name",
"age",
"isEmployee",
"address",
"hobbies"
]
}