【问题标题】:Convert JSON structure to Array in C#在 C# 中将 JSON 结构转换为数组
【发布时间】:2017-09-21 05:27:51
【问题描述】:

我需要转换这个 -

{"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

关于如何实现这一目标的任何高级想法? 提前致谢。

【问题讨论】:

  • 请告诉我们您尝试了哪些方法以及使用哪种语言解决方案?
  • 我想在 C# 中尝试一下。我没有得到实现这一目标的起点。有第一手的想法吗?

标签: c# arrays json serialization


【解决方案1】:

创建一个 JSON 模型类,您可以使用 JSONToCSharp。一旦你得到这样的 JSON 结果存储

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

它将您的结果转换为模型类的数组。然后您可以使用 foreach 循环对其进行迭代。

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

【讨论】:

  • 对不起,我最初并不清楚。我可以使用 XML 结构来实现吗?
【解决方案2】:

试试这个:)

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();

        }
    }

【讨论】:

  • 对不起,我最初并不清楚。我可以使用 XML 结构来实现吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2013-05-15
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多