marko marinovic marko marinovic - 3 months ago 5
JSON Question

c# json using newtonsoft

I read data from datagridview. For each row i create new JSONObject. I need to put every JSON object in JSONarray. here is code:

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

Answer

Maintain a list of objects (What you're trying to serialize). As you loop through, and add each element to the list of objects. At the very end, simply convert the list into a json array.

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);