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#?

4
  • What are you trying to do with it once you get the data? Commented Oct 22, 2014 at 14:14
  • Did you try with a Dictionary? Commented Oct 22, 2014 at 14:15
  • Stuff em (or something that encapsulates them) in a Dictionary? Commented Oct 22, 2014 at 14:15
  • This question has been answered load of times on here, have you even bothered to read into any? Commented Oct 22, 2014 at 14:18

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.