簡體   English   中英

在C#中將JSON結構轉換為數組

[英]Convert JSON structure to Array in C#

我需要轉換-

{"Header":{ "Number" : 101, "Total" : 100.00},
"Items" : [
{"Line" : 1, "Description": "Item 1", "Price" : 25.00, "Quantity" : 2},
{"Line" : 2, "Description": "Item 2", "Price" : 50.00, "Quantity" : 1}
]}

為此-

[
{"HeaderNumber" : 101, "Total" : 100.00, "Line" : 1, "Description": "Item 1", "Price" : 25.00, "Quantity" : 2},
{"HeaderNumber" : 101, "Total" : 100.00, "Line" : 2, "Description": "Item 2", "Price" : 50.00, "Quantity" : 1}
]
enter code here

關於如何實現此目標的任何高級建議? 提前致謝。

為此創建一個JSON Model類,您可以使用JSONToCSharp 一旦您獲得了這樣的JSON結果存儲

JsonModel[] result = JsonConvert.DeserializeObject<JsonModel[]>(postResult);

它將結果轉換為Model的Array類。 然后,您可以使用foreach循環對其進行迭代。

foreach (var item in result)
{
     item.PropertyName;
}

嘗試這個 :)

public class Header
    {
        public int Number { get; set; }
        public double Total { get; set; }
    }

    public class Item
    {
        public int Line { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
    }

    public class Source
    {
        public Header Header { get; set; }
        public List<Item> Items { get; set; }
    }

    public class Target
    {
        public int HeaderNumber { get; set; }
        public double Total { get; set; }
        public int Line { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var src = @"{""Header"":{ ""Number"" : 101, ""Total"" : 100.00},
""Items"" : [
{""Line"" : 1, ""Description"": ""Item 1"", ""Price"" : 25.00, ""Quantity"" : 2},
{""Line"" : 2, ""Description"": ""Item 2"", ""Price"" : 50.00, ""Quantity"" : 1}
]}";

            var srcObj = JsonConvert.DeserializeObject<Source>(src);

            var targetObj = srcObj.Items.Select(s => new Target()
            {
                HeaderNumber = srcObj.Header.Number,
                Total = srcObj.Header.Total,
                Description = s.Description,
                Line = s.Line,
                Price = s.Price,
                Quantity = s.Quantity
            });
            Console.WriteLine(JsonConvert.SerializeObject(targetObj));
            Console.ReadLine();

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM