0

Im using chartkick.js (which in turn uses chartjs) and I want to create the datastructure in C# for a multiple series chart, which looks like this json object:

series = [
  {name: "User1", data: {"bananas": 3, "Apples": 4}},
  {name: "User2", data: {"bananas": 5, "Apples": 3}}
]

note that in chartkick, an array of arrays will work to like so:

[["bananas", 3], ["Apples", 4]]

I've got a class to store each user's data:

public class GenericChartJsSeriesModel : ReportDataModel
{
    public string Name { get; set; }
    public ????? Data { get; set; }
}

I've tried alot, including:

Dictionary<string, int> //[{["bananas", 1]},{["appels", 1]}]
List<KeyValuePair<string, int>> //{ key: "bananas", value: 1}
string[][] //<- wont work because the values must be numeric

So the question basicly is: how to create

{"bananas": 3, "Apples": 4}

Or

[["bananas", 3], ["Apples", 4]]

Where the fruits are dynamic properties

3
  • Did you check this link I think its your solution stackoverflow.com/a/32603573/8615222 Commented May 2, 2018 at 8:29
  • Depending on de serializer dictionaries are converted as objects or as lists, i would check your serializer settings. Commented May 2, 2018 at 8:37
  • Yes that indeed is the awnser, thx Commented May 2, 2018 at 8:38

1 Answer 1

1

Perhaps not an answer (assuming usage of NewtonsoftJSON).

Implementing a custom ContractResolver will sort this out for you. You can traverse through the property and build JSON as you may wish for. There is a SO question already showing how to implement custom resolver. You can find it here.

The class may look something of this sort then:

class Sample
{
    public string Name { get; set; }

    public Collection<DataClass> Data { get; set; }
}

public class DataClass
{
    public string AttributeName { get; set; }

    public int Value { get; set; }
}

The justification for this as far as I am concerned is separation of concern. The server side code should not really be worried as to how the client side control needs the data as. Specially if you are writing APIs which may or may not be consumed by multiple client types. Server would serve the data in a specific format and it's manipulations to provide a user friendly display must be handled separately. This manipulation can either be done on the server (easily removable if needed for another client) or at the client side itself thus retaining client specific code at one place.

I hope that makes sense.

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

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.