C#Generic List to Json嵌套对象

问题描述 投票:0回答:1

我想知道如何使用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”的对象。

提前致谢!

c# json generics json.net
1个回答
1
投票

这个性质:

[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将完全看起来你想要它。

我做了一个小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.