If you are using Json.NET, you can use LINQ to JSON to restructure the JSON in a completely generic way without needing to write your own reflection code:
var jArray = JArray.FromObject(obj); // obj must serialized to an array; throw an exception otherwise.
var jObj = new JObject(jArray // Allocate new outer JSON object
.Cast<JObject>() // All array element must be json objects
.SelectMany(o => o.Properties())
.GroupBy(p => p.Name, p => p.Value) // Group all array element properties by name
.Select(g => new JProperty(g.Key, g))); // Add an array-valued property to the new outer object.
var json = jObj.ToString();
Debug.WriteLine(json);
Given the following input obj:
var obj = new List<object>
{
new { Prop1 = 57, Prop2 = 2, Prop3 = 25 },
new { Prop1 = 23, Prop2 = 4, Prop3 = 20 },
new { Prop1 = 15, Prop2 = 6, Prop3 = 32 },
};
The following JSON is produced:
{"Prop1":[57,23,15],"Prop2":[2,4,6],"Prop3":[25,20,32]}
Alternatively, if your objis strongly typed, you can manually create an intermediate anonymous type for output, like so:
var newObj = new { Prop1 = obj.Select(i => i.Prop1), Prop2 = obj.Select(i => i.Prop2), Prop3 = obj.Select(i => i.Prop3) };
Then, given the following input obj:
var obj = new[]
{
new [] { 57,2,25 },
new [] { 23,4,20 },
new [] { 15,6,32 },
}
.Select(a => new { Prop1 = a[0], Prop2 = a[1], Prop3 = a[2] });
The same JSON is produced.