Create object that contains array[] of other objects

Viewed 1417

I want to receive a json object like this:

  "datasets": [{
                "label": "# of Votes",
                "data": [20, 10, 3],
                "backgroundColor": [
                         "#ccf9d6",
                         "#ccf9d6",
                         "#ccf9d6"
                               ],
                 "borderWidth": 1
           }]

but before Serialization I have to create object and I dont know how it should look in object in code behind. I have something like this but it's wrong.

datasets = new ChartDatasets[4]
                 {
                     label = "# of Votes",
                     data = new int[3] { 20, 10, 3 },
                     backgroundColor = new string[3] { "#ccf9d6", "#ccf9d6", "#ccf9d6" },
                     borderWidth = 1
                 }

Can someone help me?

2 Answers

Although you create an array of type ChartDatasets which may hold up to four instances of that type, you don´t create an instance of this type. You´d need this instead:

datasets = new ChartDatasets[4] {
               new ChartDatasets {
                   label = "# of Votes",
                   data = new int[3] { 20, 10, 3 },
                   backgroundColor = new string[3] { "#ccf9d6", "#ccf9d6", "#ccf9d6" },
                   borderWidth = 1
               }
           }

However you can also omit the dimension and even the type of your arrays as the compiler will try to infer the right types automatically:

datasets = new [] {
               new ChartDatasets {
                   label = "# of Votes",
                   data = new [] { 20, 10, 3 },
                   backgroundColor = new [] { "#ccf9d6", "#ccf9d6", "#ccf9d6" },
                   borderWidth = 1
               }
           }

As an aisde you should consider to name instances of your type in singular, unless they really represent some kind of a collection. In your case you have an array (which surely is a collection) of instances of type CharDataset.

There is a neat website that translates JSON to nice C# code. Your question is tagged as C# so I am guessing that i what you want.

It outputs this for your code:

public class Dataset
{
    public string label { get; set; }
    public List<int> data { get; set; }
    public List<string> backgroundColor { get; set; }
    public int borderWidth { get; set; }
}

public class RootObject
{
    public List<Dataset> datasets { get; set; }
}

As far as creating an object that has an array of other objects, I'd recommend a the approach from the code above where you have a list of classes and each class has a number of objects

Related