我有一种情况,需要将json数据格式化为以下格式。
[WebMethod]
public static string ConvertDatadttoString(string appName)
{
var sample = new List<SampleClass>
{
new SampleClass()
{
columns = new List<SampleItem>()
{
new SampleItem() {title = "NAME" },
new SampleItem() {title = "COUNTY" },
},
data = new List<List<string>>()
{
new List<string> { "John Doe", "Fresno" },
new List<string> { "Billy", "Fresno" },
new List<string> { "Tom", "Kern" },
new List<string> { "King Smith", "Kings" },
}
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(sample);
return json;
}
public class SampleClass
{
public IEnumerable<SampleItem> columns { get; set; }
public IEnumerable<IEnumerable<string>> data { get; set; }
}
public class SampleItem
{
public string title { get; set; }
}
上面的代码为我提供了正确的json数据,但我需要对代码进行一些修改,以便它可以从我的源代码中获取数据。首先,new SampleItem() {title = "NAME" },
需要从类似的字符串中填充
string columnNames = "Name,County";
string[] arrcolumnNames = columnNames.Split(',');
其次需要从.net DataTable
中填充new List<string> { "John Doe", "Fresno" },
。如何做到。
我尝试添加for循环并添加字符串数组中的值:
for(int i = 0; i <= arrcolumnNames.Length; i++)
{
new SampleItem() { title = arrcolumnNames[i] }
}
但我犯了一个错误。
试试这个
public static string ConvertDatadttoString(string appName = "")
{
var columnNames = "Name,County";
var employees = CreateEmployeesTable();
var sample = new List<SampleClass>
{
new SampleClass()
{
columns = columnNames.Split(',').Select(x=> new SampleItem
{
title = x
}),
data = employees.AsEnumerable().Select(row=> new List<string>
{
row.Field<string>("EmployeeName"),
row.Field<string>("Company")
})
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(sample);
return json;
}
专用方法CreateEmployeesTable
private DataTable CreateEmployeesTable()
{
var table = new DataTable()
{
Columns = { "EmployeeName", "Company" },
TableName = "Employees"
};
table.Rows.Add("John Doe", "Fresno");
table.Rows.Add("Billy", "Fresno");
table.Rows.Add("Tom", "Kern");
table.Rows.Add("King Smith", "Kings");
return table;
}
更新
DataRowExtensions。Field Method有五个重载。
接受整数(索引)的整数重载。如果要获取第一列,则索引将为0。所以称之为row.Field<string>(0)