【问题标题】:Dynamic columns into JSon动态列到 JSON
【发布时间】:2014-04-06 10:56:21
【问题描述】:

使用 .Net,我们目前有一个嵌套列表模型(列表中的列表),它表示数据网格,因此是行列表中的列列表 即:-

public class TableViewModel 
{
   public List<List<TableColumn>> Grid { get; set; }
}


public class TableColumn
{
    public TableColumn() { }

    public TableColumn(string columnHeader, string columnValue, int columnWidth, EnumColumnType columnType, string columnName)
    {
        this.ColumnHeader = columnHeader;
        this.ColumnValue = columnValue;
        this.ColumnWidth = columnWidth;
        this.ColumnType = columnType;
        this.ColumnName = columnName;
    }

    public string               ColumnHeader    { get; set; }
    public string               ColumnName      { get; set; }
    public string               ColumnValue     { get; set; }
    public int                  ColumnWidth     { get; set; }
    public EnumColumnType       ColumnType      { get; set; }  
}

这在从 SQL 返回动态列时效果很好,但是, 我们真正努力实现的是现在使用

将其转换为正确的 JSON
List<List<TableColumn>> lst= getlist();
return Json(lst, JsonRequestBehavior.AllowGet);

它需要表示为:-

 [
    {name: 'Moroni', age: 50},
    {name: 'Tiancum', age: 43},
    {name: 'Jacob', age: 27},
    {name: 'Nephi', age: 29},
    {name: 'Enos', age: 34}];
 ]

其中 name 和 age 是列标题(来自模型的 ColumnHeader),对应关系是值(来自模型的 ColumnValue)

Linq 将如何创建它以生成返回的正确 JSON?

非常感谢,因为我们一直在努力解决这个问题..

更新:- 以下消息的示例数据

 protected void Page_Load(object sender, EventArgs e)
{
    List<List<test>> m = new List<List<test>>();
    List<test> lt = new List<test>();

   lt.Add(new test { ColumnName = "cn1", ColumnValue = "cv1" });
   lt.Add(new test { ColumnName = "cn2", ColumnValue = "cv2" });
   lt.Add(new test { ColumnName = "cn3", ColumnValue = "cv3" });
   m.Add(lt);

  lt = new List<test>();

   lt.Add(new test { ColumnName = "cn12", ColumnValue = "cv12" });
   lt.Add(new test { ColumnName = "cn22", ColumnValue = "cv22" });
   lt.Add(new test { ColumnName = "cn32", ColumnValue = "cv32" });
   m.Add(lt);


}

public class test
{
    public string ColumnName { get; set; }
    public string ColumnValue { get; set; }
}

【问题讨论】:

  • 您使用的是什么 json 框架,例如json.net、javascriptserializer 等?
  • MVC内置的system.web.mvc.JsonResult
  • 我们正在尝试返回正确格式的 Json 以与 Angular Grid 一起使用,但努力使用 Linq 操作嵌套列表以创建此 Json
  • 我认为您需要将 List&lt;List&lt;TableColumn&gt;&gt; 转换为 List&lt;Dictionary&lt;string, string&gt;&gt; 之类的东西,然后再将其传递给 Json 方法。你试过吗?
  • 感谢您的回复,但不太确定创建字典列表会有什么不同?

标签: c# .net asp.net-mvc json linq


【解决方案1】:
var obj = m.Select(x => x.ToDictionary(y => y.ColumnName, y => y.ColumnValue))
           .ToList();

只需序列化/返回 obj。

输出:

[
  {
    "cn1": "cv1",
    "cn2": "cv2",
    "cn3": "cv3"
  },
  {
    "cn12": "cv12",
    "cn22": "cv22",
    "cn32": "cv32"
  }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2018-10-14
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多