priyeshwagh777
priyeshwagh777

Reputation: 63

Convert JSON structure to Array in C#

I need to convert this -

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

to this -

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

Any high level ideas on how I can achieve this? Thanks in advance.

Upvotes: 0

Views: 168

Answers (2)

Dan Nguyen
Dan Nguyen

Reputation: 1348

Try this :)

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

        }
    }

Upvotes: 1

Muhammad Hannan
Muhammad Hannan

Reputation: 2567

Create a JSON Model class for that you can use JSONToCSharp. Once you get your JSON result store like this

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

It will convert your result into an Array of Model class. Then you can iterate over it using foreach loop.

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

Upvotes: 1

Related Questions