{得到;组;} public string ProductName {get;组;} 公共小数UnitPrice {get;组;} public int Quantity {get;组;}}
这是一些示例JSON
{ … // JSON 数据 </跨度> 在上面 “交易数据”: { “命令”: [{ “orderId”:111, “orderDescription”:“巨型食品 市场 </跨度> ” “orderItems”:[{ “productId”:65, “productName”:“干牛肉
首先,类名与您的问题中的名称不同。
您已将类声明为 Order 和 OrderDetails 在您正在使用的代码中 OrderModel 和 OrderDetailModel 。
Order
OrderDetails
OrderModel
OrderDetailModel
使用一个名称并使类受保护或不私有。
您的问题的解决方案是使用以下类结构和使用 JsonConvert 。
JsonConvert
public class Response { [JsonProperty("transactionData")] public TransactionData TransactionData { get; set; } } public class TransactionData { [JsonProperty("orders")] public List<Order> Orders { get; set; } } public class Order { [JsonProperty("orderId")] public string OrderId { get; set; } [JsonProperty("orderDescription")] public string OrderDescription { get; set; } [JsonProperty("orderItems")] public List<OrderDetail> OrderItems { get; set; } // Collection of OrderDetails } public class OrderDetail { [JsonProperty("productId")] public string ProductId { get; set; } [JsonProperty("productName")] public string ProductName { get; set; } [JsonProperty("unitPrice")] public decimal UnitPrice { get; set; } [JsonProperty("quantity")] public int Quantity { get; set; } }
然后Desrialize
string jsonResponse = @"{ 'transactionData': { 'orders': [{ 'orderId': 111, 'orderDescription': 'Giant Food Mart', 'orderItems': [{ 'productId': 65, 'productName': 'Dried Beef', 'unitPrice': 10.00, 'quantity': 7 }, { 'productId': 23, 'productName': 'Carrots', 'unitPrice': 1.25, 'quantity': 100 } ] }, { 'orderId': 112, 'orderDescription': 'Bob\'s Corner Variety', 'orderItems': [{ 'productId': 523, 'productName': 'Red Licorice', 'unitPrice': 0.50, 'quantity': 27 }, { 'productId': 321, 'productName': 'Gummy Worms', 'unitPrice': 1.50, 'quantity': 50 } ] } ] } }"; var transactionData = JsonConvert.DeserializeObject<Response>(jsonResponse);
我得到了LINQ语句来读取你的JSON,你抓住了transactionData但没有得到它下面的订单节点。请参阅评论,其中概述了一些更改:
var orders = transactionData["orders"] .Select(x => new OrderModel { OrderId = (int)x["orderId"], OrderDescription = (string)x["orderDescription"], OrderItems = x["orderItems"] .Select(y => new OrderDetailModel { ProductId = (string)y["productId"], ProductName = (string)y["productName"], UnitPrice = (decimal)y["unitPrice"], // casting to decimal but you have a string Quantity = (int)y["quantity"] }).ToList() }); public class OrderModel { public int OrderId { get; set; } public string OrderDescription { get; set; } public List<OrderDetailModel> OrderItems { get; set; } // Collection of OrderDetails } public class OrderDetailModel { public string ProductId { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } public int Quantity { get; set; } }
.Net小提琴: https://dotnetfiddle.net/bcR7Io