如果我有如下架构:
{
"id": "http://example.com/my_application",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "my_application_schema",
"additionalProperties": false,
"definitions": {
"NumberField": {
"type": "number",
"min": 0,
"max": 2147483647
},
"StringField": {
"type": "string",
"minLength": 1,
"maxLength": 12
},
"MainObject": {
"type": "object",
"additionalProperties": false,
"properties": {
"object1": {
"$ref": "#/definitions/Object1"
},
"object2": {
"$ref": "#/definitions/Object2"
}
},
"minProperties": 1,
"maxProperties": 1
},
"Object1": {
"type": "object",
"additionalProperties": false,
"properties": {
"field1": {
"$ref": "#/definitions/NumberField",
"proto_field": 1
}
},
"required": [
"field1"
]
},
"Object2": {
"type": "object",
"additionalProperties": false,
"properties": {
"field1": {
"$ref": "#/definitions/StringField",
"proto_field": 1
}
},
"required": [
"field1"
]
}
},
"type": "object",
"properties": {
"Content": {
"$ref": "#/definitions/MainObject"
}
}
}
我正在使用以下代码生成一组 C# 类:
NJsonSchema.JsonSchema4 schema = await NJsonSchema.JsonSchema4.FromFileAsync(<path to schema>);
var generator = new CSharpGenerator(schema);
var file = generator.GenerateFile();
并且,使用生成的类,执行以下操作:
My_application_schema o = JsonConvert.DeserializeObject<My_application_schema>(@"
{
'Content': {
'object1': {
'field1': 20
}
}
}");
然后反序列化完成而没有错误,但生成的对象o包含对object1和object2的引用,尽管object2的所有成员都是空的。
JsonSerializerSettings settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
};
String s = Newtonsoft.Json.JsonConvert.SerializeObject(o, settings);
// {"Content":{"object1":{"field1":20.0},"object2":{}}}
我需要的是object2要么不存在于反序列化对象中,要么设置为 null。有没有办法做到这一点,无论是在模式本身还是在这个管道中涉及的各种进程之一?