简体   繁体   中英

C# , Json.net, Help required to de-serialize json

How to Deserialize the below json, passed to Post method of webapi as JToken. I have detailed the .net Model classes, Post webapi method and the actual json being sent. I tried and am tired !!! Please help.

Thanks,
Keshavan

Valid Json (jsonbody) Corresponding to Class InvoiceHandD.cs and PostInvoiceHandD method 
----------------------------------------------------------------------------------------

{"InvoiceHandDID":1,
    "Invoices":
    [{
        "InvoiceId": 0,
        "InvoiceNo":"IN001",
        "OrderId":1,
        "SupplierCode" : "MN8787",
        "InvoiceDate":"12/15/2015", 
        "InvoiceAmount" :9000,
        "PayStatus":"Paid", 
        "VATTin":"NL001", 
        "GSTTin":"NL007"
    }],
    "InvoiceItems":
    [{
        "InvoiceDetailId":0,
        "InvoiceId":0,
        "ProductCode":"NG001",
        "ProductDesc":"NG002",
        "Specifications":"specs",
        "Quantity":700,
        "ItemValue":9000,
        "ItemStatus":"Paid"
    },
    {   "InvoiceDetailId":0,
        "InvoiceId":1,
        "ProductCode":"NG0010",
        "ProductDesc":"NG0020",
        "Specifications":"specstest",
        "Quantity":70080,
        "ItemValue":900080,
        "ItemStatus":"Not Paid"
    }]
}

WebApi Post Method (.net 4.5)
------------------

        // POST: api/InvoiceHandDs
        [ResponseType(typeof(InvoiceHandD))]
        public HttpResponseMessage PostInvoiceHandD([FromBody]JToken jsonbody)
        {
            //  Jtoken below is used instead of string becasue of jsonbody goes null if it is string
            JsonHelper helper = new JsonHelper();
            InvoiceHandD invoiceHandD = new InvoiceHandD();
            invoiceHandD = helper.ConvertJSonToObject<InvoiceHandD>(jsonbody);
            invoiceHandD.InvoiceHandDID = 1;
            for (int i = 0; i < invoiceHandD.Invoices.Count; i++)
            {
                db.Invoices.Add(invoiceHandD.Invoices[i]);
            }
            for (int i = 0; i < invoiceHandD.InvoiceDetails.Count; i++)
            {
                db.InvoiceDetails.Add(invoiceHandD.InvoiceDetails[i]);
            }
            db.SaveChanges();
            invoiceHandD = null;
            return new HttpResponseMessage(HttpStatusCode.Created);
        }


InvoiceHandD    Corresponding to Json being sent (jsonbody)
-----------------------------------------------------------

using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using MvcCashInvoice.Models;
using System.Collections.Generic;

namespace MvcCashInvoice.Helper
{
    public class InvoiceHandD
    {
        public int InvoiceHandDID { get; set; }
        public List<Invoice> Invoices = new List<Invoice>();
        public List<InvoiceDetail> InvoiceDetails = new List<InvoiceDetail>();
    }
}

Invoice (Model)
-------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace MvcCashInvoice.Models
{
    public class Invoice
    {
        [Key]
        public int InvoiceId { get; set; }
        public string InvoiceNo { get; set; }
        public int OrderId { get; set; }
        public string SupplierCode { get; set; }
        public DateTime InvoiceDate { get; set; }
        public double InvoiceAmount { get; set; }
        public string PayStatus { get; set; }
        public string VATTin { get; set; }
        public string GSTTin { get; set; }
        [Timestamp]
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public byte[] Timestamp { get; set; }
        public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }

        public Invoice()
        {
            // Setting default values here
            InvoiceId = 0;
            InvoiceNo = "";
            OrderId = 0;
            SupplierCode = "";
            InvoiceDate = new DateTime();
            InvoiceAmount = 0;
            PayStatus = "";
            VATTin = "";
            GSTTin = "";
            InvoiceDetails = new List<InvoiceDetail>();
        }
    }
}

InvoiceDetail (Model)
---------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace MvcCashInvoice.Models
{
    public class InvoiceDetail
    {
        [Key]
        public int InvoiceDetailId { get; set; }
        public int InvoiceId { get; set; }
        public string ProductCode { get; set; }
        public string ProductDesc { get; set; }
        public string Specifications { get; set; }
        public int Quantity { get; set; }
        public double ItemValue { get; set; }
        public string ItemStatus { get; set; }
        [Timestamp]
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public byte[] Timestamp { get; set; }
        [Required]
        public virtual Invoice invoice { get; set; }
    }
}

public T ConvertJSonToObject<T>(JToken jsonString)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString.ToString()));
    T obj = (T)serializer.ReadObject(ms);
    return obj;
}

就这么简单:

InvoiceHandD invoiceHandD = Newtonsoft.Json.JsonConvert.DeserializeObject<InvoiceHandD>(jsonString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM