I get JSON data from [HttpPost]
in below format. I want to de-serialize to two C# Models.
data {{
"invoiceNumber": "55",
"invoiceDate": "2018-10-25T13:16:37.843Z",
"invoiceValue": 55,
"remarks": null,'
"items": [
{
"gRNNo": "0000000",
"itemCode": 1,
"itemDesc": "Lux",
"qty": "2",
},
{
"gRNNo": "0000000",
"itemCode": 2,
"itemDesc": "Rexona",
"qty": "1"
}
]
}}
I am able to get Header data but items array.
PurHeader purHeader = JsonConvert.DeserializeObject<PurHeader>(data.ToString()); //Working for Header
but failed in getting array data. I tried following.
List<PurDetail> purDetail = JsonConvert.DeserializeObject<List<PurDetail>>(data["items"].ToString());
var purDetail = JsonConvert.DeserializeObject<PurDetail[]>(data["items"].ToString());
My Classes - I use them in Code First. And data
json comes from Angular 7 ReactiveForms
public class PurHeader
{
public string GRNNo { get; set; }
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public decimal InvoiceValue { get; set; }
public string Remarks { get; set; }
public ICollection<PurDetail> PurDetail { get; set; }
}
public class PurDetail
{
public string GRNNo { get; set; }
public string ItemCode { get; set; }
public string ItemDesc { get; set; }
public decimal Qty { get; set; }
[ForeignKey("GRNNo")]
public PurHeader PurHeader { get; set; }
}
Your JSON is malformed, I hope that's just a typo in your question. However, you should be able to parse the whole set with these classes:
public class Rootobject
{
public string invoiceNumber { get; set; }
public DateTime invoiceDate { get; set; }
public int invoiceValue { get; set; }
public object remarks { get; set; }
public Item[] items { get; set; }
}
public class Item
{
public string gRNNo { get; set; }
public int itemCode { get; set; }
public string itemDesc { get; set; }
public string qty { get; set; }
}
Rootobject purHeader = JsonConvert.DeserializeObject<Rootobject>(data.ToString());
Also see my answer here on how to easily derive classes from XML (same applies to JSON): Parse This XML to object
Assuming your data
doesn't have two {{
your code should work. But you could do it without casting to string , just:
var purHeader = data.ToObject<PurHeader>();
var purDetails = data["items"].ToObject<PurDetail[]>();
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.