3

I have a Dictionary<string,int[]> that I need to serialize to JSON. Using the default formatter, I get

{"blah": [0,1,2,3], "yada": [0,1,2,3]}

What I need is something like this

[{ name: "blah", data: [0,1,2,3]}, name: "yada", data: [0,1,2,3] }]

What's the best/easiest way to achieve this? Should I write a custom serializer class? Or is there a different collection type that would work better than Dictionary?

Jason
  • 86,222
  • 15
  • 131
  • 146

1 Answers1

2

With a little bit of LINQ you can easily transform your dictionary to your format:

var dict = new Dictionary<string, int[]>
    {
        {"blah", new[] {0, 1, 2, 3}},
        {"yada", new[] {0, 1, 2, 3}}
    };
var transformedData = dict.Select(e => new {name = e.Key, data = e.Value});
var json = JsonConvert.SerializeObject(transformedData);

Or you can create a custom JsonConverter which do this conversion.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • excellent suggestion, thanks! Only issue is that name and data are serialized as "name" and "data". Any ideas? – Jason Mar 30 '13 at 07:53
  • The JSON format uses quotes around attribute names. So strictly speaking `[{ name: "blah", data: [0,1,2,3]}, name: "yada", data: [0,1,2,3] }]` **is not a valid JSON document** because the `name` and `data` are not quoted. However with some hacking JSON.net can be convinced to not generate a valid JSON: http://stackoverflow.com/questions/7553516/json-net-serialize-property-name-without-quotes – nemesv Mar 30 '13 at 07:57