ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

(Json)序列化场景,动态属性平级扩展

2026/9/12 20:46:50 拓冰建站 浏览量
(Json)序列化场景,动态属性平级扩展 我的业务需要根据不同的部门生成不同的json动态的生成平级属性部门多单独写很麻烦变化少写继承也可以publicclassDepartmentDto{[JsonProperty(Personal Mobile 1)]publicstringPersonalMobile1{get;set;}[JsonExtensionData]publicIDictionarystring,JTokenAttributesData{get;set;}publicvoidAddPrefix(AttributesDtovalue){AttributesDatanewDictionarystring,JToken();if(valuenull||string.IsNullOrEmpty(value.Department))return;stringprefixvalue.Department;varpropsvalue.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);foreach(varpinprops){if(p.GetIndexParameters().Length0)continue;varvalp.GetValue(value);if(valnull)continue;// 忽略 null 值属性if(p.NameRecover)AttributesData[$Recover_{prefix}]JToken.FromObject(val);elseAttributesData[${prefix}_{p.Name}]JToken.FromObject(val);}}}publicclassAttributesDto{publicstringRecover{get;set;}publicstringDepartment{get;set;}publicstringName{get;set;}publicstringEmail{get;set;}publicDateTimeOffset?Date{get;set;}}具体的调用AttributesDtoattrnewAttributesDto();attr.DepartmentABC;attr.NameAA;attr.Email012QQ.COM;attr.DateDateTimeOffset.UtcNow;DepartmentDtodepartmentnewDepartmentDto();department.PersonalMobile112345678;department.AddPrefix(attr);varjsonStr1GetSerializeObject(department);效果部门是ABC时json如下{“Personal Mobile 1”: “12345678”,“Recover ABC”: “recover”,“ABC_Department”: “ABC”,“ABC_Name”: “AA”,“ABC_Email”: “012QQ.COM”,“ABC_Date”: “2026-09-10T09:44:24Z”}部门是AEC时json如下{“Personal Mobile 1”: “12345678”,“Recover AEC”: “recover”,“AEC_Department”: “AEC”,“AEC_Name”: “AA”,“AEC_Email”: “012QQ.COM”,“AEC_Date”: “2026-09-10T09:43:12Z”}方法2继承publicclassDepartmentDto{[JsonProperty(Personal Mobile 1)]publicstringPersonalMobile1{get;set;}}publicclassABCAttrDto:DepartmentDto{[JsonProperty(Recover ABC)]publicstringRecover{get;set;}}publicclassAECAttrDto:DepartmentDto{[JsonProperty(Recover AEC)]publicstringRecover{get;set;}}具体调用DepartmentDtodepartmentnewDepartmentDto();AECAttrDtoattrnewAECAttrDto();departmentattr;department.PrimaryMobile112345678;