Christoph Adamakis Christoph Adamakis - 1 month ago 10
C# Question

JsonConvert, JObject, JProperty

I have the following code that creates NewtonSoft Jobjects

JObject o = new JObject(new JProperty("DataSources", new JArray(from p in repDatasource.DataSources select JObject( JProperty("Columns", new JArray (from q in p.columns select new JObject(new JProperty("Name", q.Name),new JProperty("Type", q.Type))))))));


that produces a Json Object like this. The DataSources and Collumns are actually Jarrays

{
"DataSources": [{
"Columns": [{
"Name": "OSHYPROJECT__ProjectStatus",
"Type": "System.String"
}, {
"Name": "OSHYPROJECT__Pic",
"Type": "System.String"
}]
}, {
"Columns": [{
"Name": "Complaint__Brand",
"Type": "System.Int32"
}, {
"Name": "Complaint__Group",
"Type": "System.Int32"
}]
}]
}


I want to get a Json that instead of arrays is creating something like this (see that instead of arrays, there exist indexes)

"DataSources": {
"0": {
"Columns": {
"0": {
"Name": "CategoryID",
"Type": "System.String"
},
"1": {
"Name": "CategoryName",
"Type": "System.String"
}
},
"NameInSource": "Dk"
},
"1": {
"Ident": "StiDataTableSource",
"Columns": {
"0": {
"Name": "pColumn1",
"Type": "System.String"
},
"1": {
"Name": "pColumn2",
"Type": "System.String"
}
},
"NameInSource": "Dk"
}
}


Any Ideas?

Answer

You need a dictionary (with an int key) instead of a list or array. Then you can serialize it to json with the structure you want.

In very general terms, you could do something like this (assuming dataSources is a list):

var myDictionary = dataSources.Select((o,idx) => new { o, idx })
                              .ToDictionary(k => k.idx, v => v.o);

var json = JsonConvert.SerializeObject(myDictionary);

Of course, your code will be a little bit more complicated because you need to convert both the DataSource and the Columns within, but the principle is the same.

I'll also add that it's much easier to create a regular .NET object and then serialize it than to muck about with JObject and JArray directly. Those objects are low level and you shouldn't really need to mess with them unless you need some very particular handling of serialization.