21

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?

1
  • 1
    You can deserialize it like a anonymous array: var result = JsonConvert.DeserializeAnonymousType(jsonArray, new[] { new { Name = "" } }); Commented Oct 22, 2018 at 10:14

3 Answers 3

32

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You can deserialize to dynamic object by this.

dynamic result = JsonConvert.DeserializeObject(jsonArray);

1 Comment

or like this var result2 = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic[]>(jsonArray); - You can acess it like result2[0].Name
3

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);

1 Comment

Thanks for your answer. Is there any way of ensure that Name or Age are the correct types? Or is that not applicable for anonymous types when deserialising json?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.