c# json數組動態欄位名

來源:互聯網
上載者:User

標籤: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數組動態欄位名

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.