c#json使用newtonsoft

时间:2016-08-13 10:04:32

标签: c# json json.net

我从datagridview读取数据。对于每一行,我创建新的JSONObject。我需要将每个JSON对象放在JSONarray中。这是代码:

PodaciAnaliza podaciAnaliza = new PodaciAnaliza();
string[] test = new string[100];
podaciAnaliza.Sesija = DateTime.Now.ToString("MM/dd/yyyy h:mm tt");


int counter = 1;
foreach (DataGridViewRow row in glProstor.Rows)
{
    if (counter != glProstor.Rows.Count)
    {
         //add if not null  
        podaciAnaliza.Spin = row.Cells["brojSpina"].Value.ToString();
        podaciAnaliza.EditK1 = row.Cells["editKontra1"].Value.ToString();
        podaciAnaliza.EditI1 = row.Cells["editIsta1"].Value.ToString();
        podaciAnaliza.EditK2 = row.Cells["editKontra2"].Value.ToString();                 
        podaciAnaliza.EditI2 = row.Cells["editIsta2"].Value.ToString();

        test[counter] = JsonConvert.SerializeObject(podaciAnaliza);
        counter++;
    }

}//end of foreach

1 个答案:

答案 0 :(得分:0)

维护对象列表(您要序列化的内容)。循环时,将每个元素添加到对象列表中。最后,只需将列表转换为json数组。

var objList = new List<PodaciAnaliza>();


int counter = 1;
foreach (DataGridViewRow row in glProstor.Rows)
{
    if (counter != glProstor.Rows.Count)
    {
        var podaciAnaliza = new PodaciAnaliza();
        podaciAnaliza.Sesija = DateTime.Now.ToString("MM/dd/yyyy h:mm tt");

        //add if not null  
        podaciAnaliza.Spin = row.Cells["brojSpina"].Value.ToString();
        podaciAnaliza.EditK1 = row.Cells["editKontra1"].Value.ToString();
        podaciAnaliza.EditI1 = row.Cells["editIsta1"].Value.ToString();
        podaciAnaliza.EditK2 = row.Cells["editKontra2"].Value.ToString();                 
        podaciAnaliza.EditI2 = row.Cells["editIsta2"].Value.ToString();

        objList.Add(podaciAnaliza);
        counter++;
    }

}//end of foreach

//Seralized list:
var list = JsonConvert.SeralizeObject(objList);