0

I have a class called Attributes

public class Attributes
{
    public string Length { get; set; }
    public string Size { get; set; }
    public string Color { get; set; }
    public string Material { get; set; }
    public string Diameter { get; set; }
}

This class is populated from a call to a web service that returns JSON. The web service returns a different set of attributes each time and it is not possible to define all the attributes at compile time as this could run into thousands.

What is the best way to model such a class in c#?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

2 Answers2

3

You could use an ExpandoObject for that. In fact, the ExpandoObject is just a wrapped Dictionary<string, object>.

You can directly 'create' properties:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";

Or query the underlying dictionary:

dynamic employee = new ExpandoObject();
((IDictionary<string, object>)employee).Add("Name", "John Smith");

What ever your use is, it is possible with ExpandoObject. You can even mix both usages.

Also, this wraps perfectly using JSON.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

I recommend using DataContractJsonSerializer to perform the deserialization of JSON data. Use DataContractJsonSerializer.UseSimpleDictionaryFormat set to true, to have the result be a Dictionary<string, object> Type.

Pretty easy to use.

fooser
  • 822
  • 6
  • 14