嵌套JSON序列化问题:SerializeJsonBody字段定义报错及解决尝试
C#嵌套类JSON序列化失败及解决方法
问题背景
尝试序列化指定结构的JSON,已创建对应C#辅助类,但提示SerializeJsonBody无可用填充字段;深层类定义正常,却无法生成完整目标JSON。
目标JSON结构
{"invoiceHash": { "hashSHA":{"algorithm": "SHA-256","encoding": "Base64","value": "{0}"},"fileSize": "{1}"}, "invoicePayload":{"type": "plain","invoiceBody": "{2}"}}
对应C#类定义
public class SerializeJsonBody { public invoiceHash invoiceHash { get; set; } public invoicePayload invoicePayload { get; set; } } public class invoiceHash { public hashSHA hashSHA { get; set; } public string fileSize { get; set; } } public class hashSHA { public string algorithm { get; set; } public string encoding { get; set; } public string value { get; set; } } public class invoicePayload { public string type { get; set; } public string invoiceBody { get; set; } }
错误赋值代码
SerializeJsonBody body = new SerializeJsonBody { algorithm = "SHA-256", encoding = "Base64", value = "", fileSize = "", type = "plain", invoiceBody = "" }; string json = JsonConvert.SerializeObject(body, Formatting.Indented);
问题根源
SerializeJsonBody本身并不包含algorithm、encoding等字段,这些属性属于它的嵌套子类(hashSHA、invoicePayload)。直接在SerializeJsonBody实例初始化时赋值这些字段,编译器会报错,且因未正确初始化嵌套对象,序列化后无法生成完整JSON结构。
修正后可行代码
SerializeJsonBody body = new SerializeJsonBody { invoiceHash = new invoiceHash { hashSHA = new hashSHA { algorithm = "SHA-256", encoding = "Base64", value = base64hash }, fileSize = lenght }, invoicePayload = new invoicePayload { type = "plain", invoiceBody = base64 } }; string json = JsonConvert.SerializeObject(body, Formatting.Indented);
方案验证
你找到的修正方案是正确且最优的:通过嵌套初始化每个子对象,确保SerializeJsonBody的所有嵌套属性都被正确实例化并赋值,序列化后即可生成符合目标结构的完整JSON。
内容的提问来源于stack exchange,提问作者Tweene
相关产品推荐
相关产品推荐

