如何让C# Documents类的DocumentItem数组在JSON中正常序列化?
问题
我有一个名为Documents的类,其中包含一组DocumentItem对象,希望这组对象能出现在存入数据库的JSON中,但目前没显示出来。需要后端把这个数组像其他字段一样在JSON里展示。
当前生成的JSON
{ "id": "string", "title": "string", "icon": "string", "link": "string" }
我的C#代码
Documents类
public class Documents { [BsonId] [JsonIgnore] public ObjectId DocumentsId { get; set; } public string Id { get => DocumentsIdToString(); set { DocumentsIdToString(); } } [Required] public string Title { get; set; } = null!; [Required] public string Icon { get; set; } = null!; [Required] public string Link { get; set; } = null!; private DocumentItem[] Docs { get; set; } = null!; public Documents() { Docs = new DocumentItem[] { new DocumentItem("Capex Request","CX", 1), new DocumentItem("Cash Request","CR", 1), new DocumentItem("Stores Request","SR", 1), new DocumentItem("Quotation","QT", 1) }; } private string DocumentsIdToString() { return DocumentsId.ToString(); } }
DocumentItem类
public class DocumentItem { public string Name { get; set; } = null!; public string Prefix { get; set; } = null!; public int Module { get; set; } public DocumentItem(string Name, string Prefix, int Module) { this.Name = Name; this.Prefix = Prefix; this.Module = Module; } }
期望生成的JSON
{ "id": "string", "title": "string", "icon": "string", "link": "string", "docs": [ { "name": "Capex Request", "prefix": "CX", "module": 1 }, { "name": "Cash Request", "prefix": "CR", "module": 1 }, { "name": "Stores Request", "prefix": "SR", "module": 1 }, { "name": "Quotation", "prefix": "QT", "module": 1 } ] }
解决方案
问题核心是Docs字段的访问修饰符为private,JSON序列化器仅处理公共(public)成员,因此该数组不会被序列化到JSON中。
修改步骤:
- 将
Docs字段的访问修饰符从private改为public,让序列化器能够识别并处理它。 - 若需要JSON中的字段名为小写
docs(与期望格式匹配),可添加[JsonPropertyName("docs")]特性(需引用System.Text.Json.Serialization命名空间)。
修改后的Documents类关键代码:
using System.Text.Json.Serialization; public class Documents { // 其他成员保持不变... [JsonPropertyName("docs")] public DocumentItem[] Docs { get; set; } = null!; // 构造函数和其他方法保持不变... }
另外,你的Id属性setter逻辑存在问题,当前仅调用DocumentsIdToString()但未给DocumentsId赋值,建议修正为:
public string Id { get => DocumentsId.ToString(); set => DocumentsId = ObjectId.Parse(value); }
完成上述修改后,序列化生成的JSON就会包含docs数组,完全符合期望格式。
内容的提问来源于stack exchange,提问作者ohrayo
相关产品推荐
相关产品推荐

