標籤:val ora dict 產生 姓名 setting text 使用 sys
根據給定的列名動態產生json數組
List<string> cols = new List<string>() { "姓名","性別","年齡"};
1.使用JArray,JObject對象
//JObject JArray arr = new JArray(); JObject obj = new JObject(); foreach (var col in cols) { obj[col] = col + "_test"; } arr.Add(obj); //獲得對象的所有欄位名 var itemProperties = ((JObject)arr[0]).Properties().ToList(); foreach (var item in itemProperties) { var v = item.Name+":"+item.Value; } string json1 = JsonEncode(arr);
2.使用Datatable
//Datatable DataTable dt = new DataTable(); var row = dt.NewRow(); foreach (var col in cols) { dt.Columns.Add(col); row[col] = col + "_test"; } dt.Rows.Add(row); string json2 = JsonEncode(dt); //var colName=dt.Columns[0].ColumnName;
3.使用Dynamic對象
//Dynamic http://www.cnblogs.com/xuejianxiyang/p/4964739.html dynamic dobj = new System.Dynamic.ExpandoObject(); var dic = (IDictionary<string, object>)dobj; foreach (var col in cols) { dic[col] = col + "_test"; } foreach (var fieldItem in (IDictionary<String, Object>)dobj) {//獲得對象的所有欄位名 var v = (fieldItem.Key + ": " + fieldItem.Value); } List<System.Dynamic.ExpandoObject> list = new List<System.Dynamic.ExpandoObject>(); list.Add(dobj); string json3 = JsonEncode(list);
public static string JsonEncode<T>(T jsonstruct, bool withIndentFormat = true)
{
//var setting=new JsonSerializerSettings();
//setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
Formatting format = Formatting.Indented;
if (!withIndentFormat)
{
format = Formatting.None;
}
return JsonConvert.SerializeObject(jsonstruct, format,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
});
}
From:http://www.cnblogs.com/xuejianxiyang/p/6639610.html
c# json數組動態欄位名