如何编写匹配指定JSON结构的C#类?现有模型序列化报错
问题描述
我有一段需从JavaScript提交至API的JSON字符串,结构如下:
{ "model": "kpi.availability", "typeId": "kpi.availability", "name": "Availability", "description": "", "version": "1.0.0", "properties": { "X": { "dataType": "string", "value": "" }, "Y": { "dataType": "number", "value": 0, "isMandatory": true }, "Z": { "dataType": "number", "value": 0, "isMandatory": true } } }
其中properties的键可自定义且数量不固定。我现有C#模型无法正常工作:
public class KPIType{ public string model { get; set; } public string typeId { get; set; } public string name { get; set; } public string description { get; set; } public int version { get; set; } public IDictionary<string, PropertyItem>[] properties { get; set; } //public List<IDictionary<string, PropertyItem>> properties { get; set; } //Didn't work } public class PropertyItem { public string dataType { get; set; } public string value { get; set; } public bool isMandatory { get; set; } }
尝试发送数据至后端时,客户端报错:
"The JSON value could not be converted to System.Collections.Generic.IDictionary`2[System.String,ABB.Advanced.Services.Management.Controllers.PropertyItem][]. Path: $.kpiType.properties | LineNumber: 0 | BytePositionInLine: 294."
修正方案
问题集中在类型不匹配,修正后的C#模型如下:
public class KPIType{ public string model { get; set; } public string typeId { get; set; } public string name { get; set; } public string description { get; set; } public string version { get; set; } // 改为string,匹配JSON的版本号格式 public IDictionary<string, PropertyItem> properties { get; set; } // 去掉数组/列表,直接用字典映射JSON对象 } public class PropertyItem { public string dataType { get; set; } public object value { get; set; } // 用object兼容string和number类型 public bool? isMandatory { get; set; } // 改为可空bool,适配部分属性无该字段的情况 }
关键修正点说明
properties类型:JSON里的properties是单层键值对对象,不是数组/列表,直接用IDictionary<string, PropertyItem>就能正确映射。version类型:JSON中版本号是带小数点的字符串("1.0.0"),无法转换为int,必须改为string类型。value类型:JSON中value可能是字符串或数字,用object可兼容两种类型;如果业务能保证类型统一,也可对应改为string或double。isMandatory类型:部分属性(如X)没有该字段,改为可空bool?可避免反序列化时因缺失字段报错。
内容的提问来源于stack exchange,提问作者B.j
相关产品推荐
相关产品推荐

