将项目追加到对象



>我创建了一个 Linq 语句来从数据库中获取项目列表。所以我需要通过查询循环并附加到对象,然后序列化,然后能够在 javascript 中用作 json。 问题是我无法附加到声明的对象"obj"。谁能帮忙??

DataContext dataContext = new DataContext();
        var query = from qr in dataContext.tblStocks
                    where qr.enable == true
                    select qr;
        var obj = new JObject();
        foreach (var item in query)
        {
            //obj = new JObject();
            obj = ( new JObject(
                    new JProperty("stockID",item.stockID),
                    new JProperty("itemDepartmentID", item.itemDepartmentID),
                    new JProperty("item" , item.item),
                    new JProperty("description", item.description),
                    new JProperty("stockAmount", item.stockAmount),
                    new JProperty("priceExlVat", item.priceExlVat),
                    new JProperty("vat", item.vat),
                    new JProperty("priceIncVAT", item.priceIncVAT),
                    new JProperty("upc1", item.upc1),
                    new JProperty("upc2", item.upc2)
                ));

       }
        var serialized = JsonConvert.SerializeObject(obj);
        return serialized;

每次通过循环重新分配obj,因此所有其他数据都将丢失。

更容易创建数组:

obj = new JArray();
foreach (var item in query) {
  obj.Add(new JObject(
            new JProperty(...),
            ...));
}

你为什么不序列化你的对象呢?

List<dynamic> obj = new List<dynamic>();
foreach(var item in query) {
    obj.Add(new
    {
        itemDepartmentID = item.itemDepartmentID,
        description = item.description,
        ...
    });
}
var serialized = JsonConvert.SerializeObject(obj);

另一种方法是,您可以在查询中使用匿名类型,并且只需序列化查询的整个查询返回 IEnumerable它会自动转换为 jsonArray:

DataContext dataContext = new DataContext();
var query = dataContext.tblStocks
    .Where(stockItem => stockItem.enable)
    .Select(stockItem => new
                        {
                            stockItem.stockID,
                            stockItem.itemDepartmentID,
                            stockItem.item,
                            stockItem.description,
                            stockItem.stockAmount,
                            stockItem.priceExlVat,
                            stockItem.vat,
                            stockItem.priceIncVat,
                            stockItem.upc1,
                            stockItem.upc2
                        });
return JsonConvert.SerializeObject(query);

相关内容

  • 没有找到相关文章

最新更新