我有一些JSON格式的订单数据,我希望用它来填充自定义对象。看看JSON.net文档,我可以使用LINQ to JSON将JSON反序列化为.NET类型。我的问题是你能用一个引用另一个自定义类作为属性的类吗?
假设我有两个班级Order
和OrderDetail
。其中Order
的属性包含OrderDetail
个对象的集合。
class Order
{
public string OrderId {get; set;}
public string OrderDescription {get; set;}
public List<OrderDetail> OrderItems {get; set;} // Collection of OrderDetails
}
class OrderDetail
{
public string ProductId {get; set;}
public string ProductName {get; set;}
public string UnitPrice {get; set;}
public int Quantity {get; set;}
}
可以使用LINQ to JSON查询数据并填充对象吗?
以下是一些示例JSON
{
"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
}
]
}
]
}
如何将OrderItems
解析为Order
对象的 Orderitems 属性,让我感到困惑
JArray parsedJson = JArray.Parse("JSON data here");
IList<Order> orders = parsedJson.Select(x => new Order
{
OrderId = (int)x["orderId"],
OrderDescription = (string)x["orderDescription"],
OrderItems = x["orderItems"], // Here is where I get stuck
}).ToList();
答案 0 :(得分:2)
你正在努力实现这一目标。使用json2csharp.com生成与JSON匹配的类。
public class OrderItem
{
public int productId { get; set; }
public string productName { get; set; }
public double unitPrice { get; set; }
public int quantity { get; set; }
}
public class Order
{
public int orderId { get; set; }
public string orderDescription { get; set; }
public List<OrderItem> orderItems { get; set; }
}
public class RootObject
{
public List<Order> orders { get; set; }
}
然后简单地反序列化为这些类。
JsonConvert.DeserializeObject<RootObject>(myJsonString);
此时,您可以使用LINQ-to-Objects执行您可能需要的任何查询。
答案 1 :(得分:1)
你非常接近,这使用linq工作,你将获得你的订单列表中的所有内容。
var parsedJson = JObject.Parse(test);
var orders = parsedJson.Values().Children()
.Select(x => new Order
{
OrderId = (int)x["orderId"],
OrderDescription = (string)x["orderDescription"],
OrderItems = JsonConvert.DeserializeObject< List<OrderDetail>>(x["orderItems"].ToString())
}).ToList();
注意:我必须改变:
public string OrderId { get; set; } //you were casting to int but had a string.
到
public int OrderId { get; set; }