Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping JSON objects with incremental names to C# models

What is the best way to map a JSON object that has a structure whereby it contains a list of objects whose names are dynamically created through incrementation?

e.g.

{"data":
 {
  "object-0":[{"id":"1","name":"John"},{"id":"2","name":"Mary"}],
  "object-1":[{"id":"3","name":"Gary"},{"id":"4","name":"Mark"}]
 }
}
like image 585
Callum Bugler Avatar asked Oct 22 '25 01:10

Callum Bugler


1 Answers

Assuming you've got a class like

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

You could deserialize this into a Dictionary<string, IEnumerable<User>> like so

Dictionary<string, IEnumerable<User>> values =
    JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<User>>>(json);

This also assumes the use of json.net

like image 51
Alex Avatar answered Oct 23 '25 14:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!