logo

C# How to deserialize a json string into a class and list of classes

Overview: This code snippet demonstrates how to create a json string that can be deserialized into a class and class list encapsulated in the parent class. A purchaseOrderView contains a list of PurchaseOrderDetailViews. The unitOfWork will use the purchaseOrderView to create the purchase order and its details in the sql table. I demonstrate how to create a json string in c# in this demonstration. I bind information from the SupplierView, Company, and 5 item master objects into the json. The unit of work will do all the rollup calculations before writing to the database.

Newtonsoft JsonConvert.DeserializeObject is used to deserialize the json structure into the class objects. The JSON view in the debugger is helpful to know whether your json string has been formatted correctly.

@""" are used to create one quote in json. A single @" is used to separate and start the c# code parsing to be inserted into the json string data.

Binding to the Json

     UnitOfWork unitOfWork = new UnitOfWork();

ItemMaster[] itemMasterLookup=new ItemMaster[5];

            itemMasterLookup[0] = await unitOfWork.itemMasterRepository.GetObjectAsync(5);
            itemMasterLookup[1] = await unitOfWork.itemMasterRepository.GetObjectAsync(6);
            itemMasterLookup[2] = await unitOfWork.itemMasterRepository.GetObjectAsync(7);
            itemMasterLookup[3] = await unitOfWork.itemMasterRepository.GetObjectAsync(8);
            itemMasterLookup[4] = await unitOfWork.itemMasterRepository.GetObjectAsync(9);


            string json = @"{
            ""DocType"" : ""OV"",
            ""PaymentTerms"" : ""Net 30"",
            ""GLDate"" : """ + DateTime.Parse("7/30/2018") + @""",
            ""AccountId"" :"  + coa.AccountId + @",
            ""SupplierId"" :" + (supplierView.SupplierId ?? 0).ToString() +@",
            ""SupplierName"" :""" + supplierView.CompanyName +@""",
            ""Description"" :""Back to School Inventory"",
            ""PONumber"" :""PO -1"",
            ""TakenBy"" : ""David Nishimoto"",
            ""BuyerId"" :"  + company.CompanyId +@",
            ""ShippedToName"" :"""+ company.CompanyName + @""",
            ""ShippedToAddress1"" :""" + company.CompanyStreet + @""",
            ""ShippedToCity"" :""" + company.CompanyCity + @""",
            ""ShippedToState"" :""" + company.CompanyState + @""",
            ""ShippedToZipcode"" :""" + company.CompanyZipcode + @""",
            ""RequestedDate"" :""" + DateTime.Parse("7/24/2018") + @""",
            ""PromisedDeliveredDate"" :""" + DateTime.Parse("8/2/2018") + @""",
            ""TransactionDate"" :""" + DateTime.Parse("7/30/2018")+ @""", 

            ""PurchaseOrderDetailViews"":[
                    {
                    ""ItemId"": 5,
                    ""OrderDate"":"""+ DateTime.Parse("7 / 30 / 2018") + @""",
                    ""OrderedQuantity"": 5,
                    ""UnitPrice"" : " + itemMasterLookup[0].UnitPrice + @",
                    ""UnitOfMeasure"" : """ + itemMasterLookup[0].UnitOfMeasure + @""",
                    ""Amount"" : " + itemMasterLookup[0].UnitPrice*5 + @",
                    ""Description"": """+itemMasterLookup[0].Description + @""",
                    ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""",
                    ""ReceivedQuantity"":0,
                    ""RemainingQuantity"":5
                    },
                    {
                    ""ItemId"": 6,
                    ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""",
                    ""OrderedQuantity"": 4,
                    ""UnitPrice"" : " + itemMasterLookup[1].UnitPrice + @",
                    ""UnitOfMeasure"" : """ + itemMasterLookup[1].UnitOfMeasure + @""",
                    ""Amount"" : " + itemMasterLookup[1].UnitPrice * 4 + @",
                    ""Description"": """ + itemMasterLookup[1].Description + @""",
                    ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""",
                    ""ReceivedQuantity"":0,
                    ""RemainingQuantity"":4
                    },
                    {
                    ""ItemId"": 7,
                    ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""",
                    ""OrderedQuantity"": 10,
                    ""UnitPrice"" : " + itemMasterLookup[2].UnitPrice + @",
                    ""UnitOfMeasure"" : """ + itemMasterLookup[2].UnitOfMeasure + @""",
                    ""Amount"" : " + itemMasterLookup[2].UnitPrice * 10 + @",
                    ""Description"": """ + itemMasterLookup[2].Description + @""",
                    ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""",
                    ""ReceivedQuantity"":0,
                    ""RemainingQuantity"":10
                    },
                    {
                    ""ItemId"": 8,
                    ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""",
                    ""OrderedQuantity"": 15,
                    ""UnitPrice"" : " + itemMasterLookup[3].UnitPrice + @",
                    ""UnitOfMeasure"" : """ + itemMasterLookup[3].UnitOfMeasure + @""",
                    ""Amount"" : " + itemMasterLookup[3].UnitPrice * 15 + @",
                    ""Description"": """ + itemMasterLookup[3].Description + @""",
                    ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""",
                    ""ReceivedQuantity"":0,
                    ""RemainingQuantity"":15
                    },
                    {
                    ""ItemId"": 9,
                    ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""",
                    ""OrderedQuantity"": 10,
                    ""UnitPrice"" : " + itemMasterLookup[4].UnitPrice + @",
                    ""UnitOfMeasure"" : """ + itemMasterLookup[3].UnitOfMeasure + @""",
                    ""Amount"" : " + itemMasterLookup[4].UnitPrice * 10 + @",
                    ""Description"": """ + itemMasterLookup[4].Description + @""",
                    ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""",
                    ""ReceivedQuantity"":0,
                    ""RemainingQuantity"":10
                    }
                ]
    }";

        
            PurchaseOrderView purchaseOrderView = JsonConvert.DeserializeObject<PurchaseOrderView>(json);

PurchaseOrderView

 public class PurchaseOrderView
    {
        public PurchaseOrderView() { }
        public PurchaseOrderView(PurchaseOrder po)
        {
            this.PurchaseOrderId = po.PurchaseOrderId;
            this.DocType = po.DocType;
            this.PaymentTerms = po.PaymentTerms;
            this.GrossAmount = po.GrossAmount;
            this.Remark = po.Remark;
            this.GLDate = po.GLDate;
            this.AccountId = po.AccountId;
            this.SupplierId = po.SupplierId;
            this.SupplierName = po.Supplier.AddressBook.Name;
            this.ContractId = po.ContractId;
            this.POQuoteId = po.POQuoteId;
            this.Description = po.Description;
            this.PONumber = po.PONumber;
            this.TakenBy = po.TakenBy;
            this.ShippedToName = po.ShippedToName;
            this.ShippedToAddress1 = po.ShippedToAddress1;
            this.ShippedToAddress2 = po.ShippedToAddress2;
            this.ShippedToCity = po.ShippedToCity;
            this.ShippedToState = po.ShippedToState;
            this.ShippedToZipcode = po.ShippedToZipcode;
            this.BuyerId = po.BuyerId;
            this.RequestedDate = po.RequestedDate;
            this.PromisedDeliveredDate = po.PromisedDeliveredDate;
            this.Tax = po.Tax;
            this.TaxCode = po.TaxCode;
            this.TransactionDate = po.TransactionDate;
            this.AmountReceived = po.AmountReceived;
            this.AmountPaid = po.AmountPaid;
        }
        public long? PurchaseOrderId { get; set; }
        public string DocType { get; set; }
        public string PaymentTerms { get; set; }
        public decimal? GrossAmount { get; set; }
        public string Remark { get; set; }
        public DateTime? GLDate { get; set; }
        public long AccountId { get; set; }
        public long SupplierId { get; set; }
        public string SupplierName { get; set; }
        public long? ContractId { get; set; }
        public long? POQuoteId { get; set; }
        public string Description { get; set; }
        public string PONumber { get; set; }
        public string TakenBy { get; set; }
        public string ShippedToName { get; set; }
        public string ShippedToAddress1 { get; set; }
        public string ShippedToAddress2 { get; set; }
        public string ShippedToCity { get; set; }
        public string ShippedToState { get; set; }
        public string ShippedToZipcode { get; set; }
        public long? BuyerId { get; set; }
        public DateTime? RequestedDate { get; set; }
        public DateTime? PromisedDeliveredDate { get; set; }
        public decimal? Tax { get; set; }
        public string TaxCode { get; set; }
        public DateTime? TransactionDate { get; set; }
        public decimal? AmountReceived { get; set; }
        public decimal? AmountPaid { get; set; }

        public IList<PurchaseOrderDetailView> 

PurchaseOrderDetailViews

PurchaseOrderDetailViews { get; set; }
    }
    public class PurchaseOrderDetailView
    {
        public PurchaseOrderDetailView() { }
        public PurchaseOrderDetailView(PurchaseOrderDetail detail)

        {
            this.PurchaseOrderDetailId = detail.PurchaseOrderDetailId;
            this.PurchaseOrderId = detail.PurchaseOrderId;
            this.Amount = detail.Amount;
            this.OrderedQuantity = detail.OrderedQuantity;
            this.ItemId = detail.ItemId;
            this.UnitPrice = detail.UnitPrice;
            this.UnitOfMeasure = detail.UnitOfMeasure;
            this.ReceivedDate = detail.ReceivedDate;
            this.ExpectedDeliveryDate = detail.ExpectedDeliveryDate;
            this.OrderDate = detail.OrderDate;
            this.ReceivedQuantity = detail.ReceivedQuantity;
            this.RemainingQuantity = detail.RemainingQuantity;
            this.Description = detail.Description;
    }
    public long PurchaseOrderDetailId { get; set; }
        public long PurchaseOrderId { get; set; }
       public decimal? Amount { get; set; }
        public decimal? OrderedQuantity { get; set; }
       public long ItemId { get; set; }
        public decimal? UnitPrice { get; set; }
        public string UnitOfMeasure { get; set; }
        public DateTime? ReceivedDate { get; set; }
        public DateTime? ExpectedDeliveryDate { get; set; }
        public DateTime? OrderDate { get; set; }
        public int? ReceivedQuantity { get; set; }
        public int? RemainingQuantity { get; set; }
        public string Description { get; set; }
    }
s