我的数据库tables
和Stores
中有两个Products
,其中包含以下字段
TBL_Store
StoreID (Primary Key)
StoreName
TBL_PRODUCT
ProductID (Primary Key)
StoreID (Foreign Key)
ProductName
INT_TYPE
我使用以下查询来创建JSON
数组
var data = context.tbl_product.Where(x => x.INT_TYPE == 1).ToList();
var json = JsonConvert.SerializeObject(data, Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
它为我提供了Repeated Entries
的所有关系表数据。
我想让我的json成为像这样的东西
[{
"Store": {
"storeid": "1",
"storename": "Nike",
"Products": [{
"ProdID": "1",
"prodName": "NikeShoes1"
}, {
"ProdID": "2",
"prodName": "NikeShoes2"
}, {
"ProdID": "3",
"prodName": "NikeShoes3"
}]
},
"Store": {
"storeid": "2",
"storename": "Biba",
"Products": [{
"ProdID": "1",
"prodName": "Biba1"
}, {
"ProdID": "2",
"prodName": "Biba2"
}, {
"ProdID": "3",
"prodName": "Biba3"
}]
}
}]
答案 0 :(得分:1)
假设您的tbl_product
中有Store
导航属性
创建帮助程序类:
[JsonObject(MemberSerialization.OptIn)]
public class Product
{
[JsonProperty("prodName")]
public string ProductName {get;set;}
[JsonProperty("ProdID")]
public int ProductId {get;set;}
}
[JsonObject(MemberSerialization.OptIn)]
public class Store
{
[JsonProperty("storeid")]
public string StoreId { get; set; }
[JsonProperty("storename")]
public string StoreName { get; set; }
[JsonProperty("Products")]
public IList<Product> Products { get; set; }
}
以所需格式获取数据(通知Include方法将禁用对商店对象的延迟加载):
var data = context.tbl_product.Where(x => x.INT_TYPE == 1).Include(x=>x.Store).ToList();
var stores = from d in data
group d by new {d.StoreID, d.StoreName} into stores
select new Store{
StoreId = stores.Key.StoreID,
StoreName = stores.Key.StoreName,
Products = stores.Select(s=>new Product{ ProductId = s.ProductID, ProductName = s.ProductName }).ToList()
};
然后您可以在商店对象上使用序列化:
var json = JsonConvert.SerializeObject(stores , Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});