如果您可以修改架构,则可以执行以下操作:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"Identifiers": {
"type": "array",
"items": {
"allOf": [
{
"$ref": "#/definitions/Identifier"
}
]
}
}
},
"required": [
"Identifiers"
],
"definitions": {
"Identifier": {
"type": "object",
"x-typeName": "Identifier",
"properties": {
"ID": {
"type": "string"
},
"IDType": {
"type": "string"
}
},
"required": [
"ID",
"IDType"
]
}
}
}
使用以下程序测试:
public static async Task Main(string[] args)
{
var json = File.ReadAllText("json-schema-sample.json");
var schema = await JsonSchema4.FromJsonAsync(json);
var csharpSetting = new CSharpGeneratorSettings {Namespace = "Generated.Json", ClassStyle = CSharpClassStyle.Poco};
var generator = new CSharpGenerator(schema, csharpSetting);
var file = generator.GenerateFile("Root");
using (var sw = File.CreateText("Generated.cs"))
{
sw.Write(file);
}
}
它生成以下类:
//----------------------
// <auto-generated>
// Generated using the NJsonSchema v9.7.7.0 (Newtonsoft.Json v9.0.0.0) (http://NJsonSchema.org)
// </auto-generated>
//----------------------
namespace Generated.Json
{
#pragma warning disable // Disable all warnings
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.7.7.0 (Newtonsoft.Json v9.0.0.0)")]
public partial class Identifier
{
[Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
public string ID { get; set; }
[Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
public string IDType { get; set; }
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
public static Identifier FromJson(string data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Identifier>(data);
}
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.7.7.0 (Newtonsoft.Json v9.0.0.0)")]
public partial class Root
{
[Newtonsoft.Json.JsonProperty("Identifiers", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
public System.Collections.ObjectModel.ObservableCollection<Identifier> Identifiers { get; set; } = new System.Collections.ObjectModel.ObservableCollection<Identifier>();
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
public static Root FromJson(string data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(data);
}
}
}