从通用列表创建所需的json数据数组

时间:2016-01-07 10:40:33

标签: c# json asp.net-mvc entity-framework json.net

我的数据库tablesStores中有两个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"
    }]
}
  }]

1 个答案:

答案 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
                        });