动态列到JSon

时间:2014-03-04 18:21:39

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

使用.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; }
}

1 个答案:

答案 0 :(得分:2)

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"
  }
]
相关问题