在C#中将数组序列化为JSON

时间:2015-11-02 09:37:59

标签: c# json

如何在c#中初始化并向json数组添加动态值?我想将每个值添加到foreach循环内的json数组。

var cookies = document.cookie.split(';');//contains all the cookies
var cookieName = []; // to contain name of all the cookies

for(i=0;i<cookies.length;i++) {
    cookieName[i] = cookies[i].split('=')[0].trim();
}

    if(cookiesName.indexOf(cookieNameYouAreLookingFor)>-1) {
        console.log("EXISTS");
    } else {
        console.log("DOESN'T EXIST");
    }

2 个答案:

答案 0 :(得分:0)

对于数组,创建一个数组并对其进行序列化。对于字典,要么创建字典(键值),要么自定义序列化(在Stack Overflow上覆盖)或使用动态对象,例如:

https://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

或者只查找serialize dynamic object json,也可以覆盖堆栈溢出。

如果您根本不知道如何序列化为JSON,请查看ASP / WebAPI教程,其中包含这些内容。

答案 1 :(得分:0)

分享我可以使用DataTable传输数据和反馈Json格式的方式,希望这是处理问题的好方法

public IHttpActionResult PostBanners(xx id)
        {
            string queryString = "select top 2 a.point,a.seq_banner  from Banners as a left join RelationCountryBanner as b on a.seq_banner = b.seq_file ";
           //string queryString = id.str;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {
                if (ConfigurationManager.ConnectionStrings["DefaultConnection"] != null)
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
                }
                else
                {
                    con.ConnectionString = "Data Source=******;Initial Catalog=B2CGlobal2010;Persist Security Info=True;User ID=*******;Password=****";
                }
                using (SqlCommand cmd = new SqlCommand(queryString.ToString(), con))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();

                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);

                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }
                    DataTable xx = (DataTable)JsonConvert.DeserializeObject(serializer.Serialize(rows), (typeof(DataTable)));
                   // return Ok(xx);
                    return Ok(serializer.Serialize(rows));
                }
            }

            return NotFound();
        }