I have a class called Documents that should have an array of DocumentItem objects and I want them to appear in the json that I want to send to the DB but they’re not. I want the backend to display the array in the json that will go the db like any other field
The Json appears like this
{
"id": "string",
"title": "string",
"icon": "string",
"link": "string"
}
{
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();
}
}
}
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;
}
}
}
I want the Json to appear like this
{
"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
}
]
}
2
Answers
By default, only
public
properties are serialized.Change the accessor from
private
topublic
.try this