我在项目中有一个 json 模式,并希望添加构建步骤以从中生成类,这些模式中包含一个对象和字符串数组,简化示例如下:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "testSchema",
"type": "object",
"properties": {
"array": {
"type": "array",
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
}
]
}
}
}
}
我正在使用NJsonSchema从此模式生成 C# 代码。结果,我得到以下输出:
//----------------------
// <auto-generated>
// Generated using the NJsonSchema v8.32.6319.16936 (http://NJsonSchema.org)
// </auto-generated>
//----------------------
namespace TestSchema
{
#pragma warning disable // Disable all warnings
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "8.32.6319.16936")]
public partial class TestSchema : System.ComponentModel.INotifyPropertyChanged
{
private System.Collections.ObjectModel.ObservableCollection<Anonymous> _array = new System.Collections.ObjectModel.ObservableCollection<Anonymous>();
[Newtonsoft.Json.JsonProperty("array", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.ObjectModel.ObservableCollection<Anonymous> Array
{
get { return _array; }
set
{
if (_array != value)
{
_array = value;
RaisePropertyChanged();
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
public static TestSchema FromJson(string data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<TestSchema>(data);
}
protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "8.32.6319.16936")]
public partial class Anonymous : System.ComponentModel.INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
public static Anonymous FromJson(string data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Anonymous>(data);
}
protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
结果我有这个奇怪的Anonymous
类,如果我尝试反序列化下面的 json 文件,我会收到一个错误:string
无法转换为Anonymous
. 要反序列化,我使用以下生成的方法:
TestSchema.FromJson
是否可以将代码生成调整为结果是一个集合,object
并在其中获得具有正确类型的反序列化对象?
{
"array": [
"stringItem1",
{
"name": "complexObj1"
}
]
}