Arnab Arnab - 4 months ago 31
C# Question

Json string to object array c#

My test json is as below..

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";

The json could have any key values and so I do not have a class to deserialize it with.. I can deserialize it as IEnumerable as below

IEnumerable<dynamic> data = JsonConvert.DeserializeObject<IEnumerable<dynamic>>(json);

I need to convert it to 2D object arrays : object[,] as below..

['John Simith',35],['Pablo Perez',34]

Any help is sincerely appreciated.


You can change from dynamic to IDictionary<string, object> in order to be able to enumerate unknown keys. Then a LINQ expression can convert it to an array, like this:

var json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";
var data = JsonConvert.DeserializeObject<IEnumerable<IDictionary<string, object>>>(json);

var array = data.Select(d => d.Values.ToArray()).ToArray();