c# json数组动态字段名
Posted Ace007
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# json数组动态字段名相关的知识,希望对你有一定的参考价值。
根据给定的列名动态生成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数组动态字段名的主要内容,如果未能解决你的问题,请参考以下文章