Lara Lara - 4 months ago 14
JSON Question

How to serialize specific Json object from C#

I have a requirement where i need to serialize

json
object in below format

[{
"columns": [{
"title": "NAME"
}, {
"title": "COUNTY"
}],
"data": [
["John Doe", "Fresno"],
["Billy", "Fresno"],
["Tom", "Kern"],
["King Smith", "Kings"]
]
}]


Here i need to get this json object from two different source, one is
Columns
and other is
data
. Columns would come from a
string
which will be comma separated as

string columnNames = "Name, County";


and
data
would come from .net Datatable like

DataTable dt = new DataTable();


I tried with below code using
JavaScriptSerializer
but i am not able to format it in the required format. Actually, shared format is required to dynamically create jquery datatable. Here is my raw code in C#.

[WebMethod]
public static string ConvertDatadttoString(string appName)
{

DataTable dt = new DataTable();

dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("County", typeof(string));

dt.Rows.Add("vo", "go.com");
dt.Rows.Add("pa", "pa.com");

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
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);
}
return serializer.Serialize(rows);
}


Above code is only serializing the
DataTable
and is not able to create in the required format. Thanks.

Answer

What I usually do, is I build a model based off of the data, and serialize that model.

This is how I'd imagine your model would look.

public class SampleClass
{
    public IEnumerable<SampleItem> columns { get; set; }
    public IEnumerable<IEnumerable<string>> data { get; set; }
}

public class SampleItem
{
    public string title { get; set; }
}

And this is how I'd imagine you'd get the sample json

var sample = new List<SampleClass>
{
    new SampleClass()
    {
        columns = new List<SampleItem>()
        {
            new SampleItem() {title = "NAME" },
            new SampleItem() {title = "COUNTY" },
        },
        data = new List<List<string>>()
        {
            new List<string> { "John Doe", "Fresno" },
            new List<string> { "Billy", "Fresno" },
            new List<string> { "Tom", "Kern" },
            new List<string> { "King Smith", "Kings" },
        }
    }
};

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(sample);

I'm sure you can figure out how to create that model based off of your real data. It's not that hard.