marto
marto

Reputation: 460

How do I deserialize an array of JSON objects to a C# anonymous type?

I have no problem deserializing a single json object

string json = @"{'Name':'Mike'}";

to a C# anonymous type:

var definition = new { Name = ""};
var result = JsonConvert.DeserializeAnonymousType(json, definition);

But when I have an array:

string jsonArray = @"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";

I am stuck.

How can it be done?

Upvotes: 21

Views: 13659

Answers (3)

Marc.2377
Marc.2377

Reputation: 8694

The solution is:

string json = @"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";

var definition = new[] { new { Name = "" } };

var result = JsonConvert.DeserializeAnonymousType(json, definition);

Of course, since result is an array, you'll access individual records like so:

string firstResult = result[0].Name;

You can also call .ToList() and similar methods on it.

Upvotes: 30

OJ Raqueño
OJ Raqueño

Reputation: 4561

One approach is to put an identifier in your JSON array string.

This code worked for me:

var typeExample = new { names = new[] { new { Name = "" } } };
string jsonArray = @"{ names: [{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]}";

var result = JsonConvert.DeserializeAnonymousType(jsonArray, typeExample);

Upvotes: 3

Power Star
Power Star

Reputation: 1894

You can deserialize to dynamic object by this.

dynamic result = JsonConvert.DeserializeObject(jsonArray);

Upvotes: 3

Related Questions