Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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?

like image 823
marto Avatar asked Aug 21 '17 12:08

marto


People also ask

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Can not deserialize JSON array?

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array.


3 Answers

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.

like image 50
Marc.2377 Avatar answered Oct 06 '22 18:10

Marc.2377


You can deserialize to dynamic object by this.

dynamic result = JsonConvert.DeserializeObject(jsonArray);
like image 41
Power Star Avatar answered Oct 06 '22 17:10

Power Star


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);
like image 3
OJ Raqueño Avatar answered Oct 06 '22 17:10

OJ Raqueño