我想知道如何使用 C# 将 C# 泛型列表导出到使用嵌套对象的 JSON 对象中,而不是 Json 数组。
我想生成的 Json 应该如下所示:
{
"sales_invoice": {
"contact_id": 201171400939013415,
"remove_invoice_sequence_id": true,
"invoice_sequence_id": "F2017004",
"reference": null,
"invoice_date": "5-1-2017",
"currency": "EUR",
"prices_are_incl_tax": false,
"details_attributes": {
"0": {
"description": "Product description",
"price": 13.80,
"amount": "10",
"tax_rate_id": 197923875808347751,
"ledger_account_id": 197923875101607508
},
"1": {
"description": "Product description",
"price": 13.80,
"amount": "10",
"tax_rate_id": 197923875808347751,
"ledger_account_id": 197923875101607508
}
}
}
}
这是我的 C# 类,包括 Json 属性:
[JsonObject(Title = "sales_invoice")]
public class SalesInvoice
{
[JsonProperty("contact_id")]
public long ContactId { get; set; }
[JsonProperty("remove_invoice_sequence_id")]
public bool RemoveInvoiceSequenceId { get; set; }
[JsonProperty("invoice_sequence_id")]
public string InvoiceSequenceId { get; set; }
[JsonProperty("reference")]
public string Reference { get; set; }
[JsonProperty("invoice_date")]
public string InvoiceDate { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("prices_are_incl_tax")]
public bool PricesAreIncludingTax { get; set; }
[JsonProperty("details_attributes")]
public List<SalesInvoiceDetails> Details { get; set; }
}
public class SalesInvoiceDetails
{
[JsonProperty("0")]
public SalesInvoiceDetailAttributes SalesInvoiceDetail { get; set; }
}
public class SalesInvoiceDetailAttributes
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("amount")]
public string Amount { get; set; }
[JsonProperty("tax_rate_id")]
public long TaxRateId { get; set; }
[JsonProperty("ledger_account_id")]
public long LedgerAccountId { get; set; }
}
那么,如何让这个"0"和"1"对象动态化呢?现在我得到一个结果,所有对象都有"0"。
提前感谢!
此属性:
[JsonProperty("details_attributes")]
public List<SalesInvoiceDetails> Details { get; set; }
应该是Dictionary<string, SalesInvoiceDetailAttributes>
而不是List<SalesInvoiceDetails>
。
您的SalesInvoiceDetails
类对于您想要的结构是多余的,应将其删除。
当您添加到此字典时,您将在此处增加密钥:
someObject.Details.Add("0", new SalesInvoiceDetailAttributes());
someObject.Details.Add("1", new SalesInvoiceDetailAttributes());
//etc
当它被序列化时,你的 json 将完全按照你想要的样子。
我在这里做了一个小提琴