[英]Dynamic columns into JSon
Using .Net, We currently have a nested list model (list within a list) that represents a grid of data,so a list of columns within a list of rows ie:- 使用.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; }
}
This works great when returning dynamic columns from SQL, how ever, what we are really struggling to achieve, is to now transpose this into correct JSON using 从SQL返回动态列时这很有用,但是,我们真正努力实现的目标是,现在将它转换为正确的JSON使用
List<List<TableColumn>> lst= getlist();
return Json(lst, JsonRequestBehavior.AllowGet);
it needs to be represented as :- 它需要表示为: -
[
{name: 'Moroni', age: 50},
{name: 'Tiancum', age: 43},
{name: 'Jacob', age: 27},
{name: 'Nephi', age: 29},
{name: 'Enos', age: 34}];
]
where name and age are column headers (ColumnHeader from the model) and the correspondence is the value (ColumnValue from the model) 其中name和age是列标题(模型中的ColumnHeader),对应关系是值(模型中的ColumnValue)
What would the Linq be to create this to produce the correct JSON which is returned? Linq将创建这个以生成返回的正确JSON是什么?
Much appreciated, as we've really been struggling with this.. 非常感谢,因为我们一直在努力解决这个问题。
UPDATE :- Sample data for below message 更新: - 以下消息的示例数据
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; }
}
var obj = m.Select(x => x.ToDictionary(y => y.ColumnName, y => y.ColumnValue))
.ToList();
Just serialize/return obj. 只需序列化/返回obj。
Output: 输出:
[
{
"cn1": "cv1",
"cn2": "cv2",
"cn3": "cv3"
},
{
"cn12": "cv12",
"cn22": "cv22",
"cn32": "cv32"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.