Gordon Hickley
Gordon Hickley

Reputation: 491

JSON convert dictionary to a list of key value pairs

I have a Dictionary <string, string>

If I Json.Encode this I get {"Apple":"Apples","Orange":"Oranges"}

How I can get this to:-

[{ value: "Apples", key: "Apple" }, { value: "Oranges", key: "Orange"}]

Preferably using Newtonsoft.Json or jQuery

Upvotes: 2

Views: 3890

Answers (2)

Vinney Kelly
Vinney Kelly

Reputation: 5095

To reiterate my comment, changing the data type from an IEnumerable> (or IDictionary) to a IList> will also cause the serialization to work "correctly" a.k.a. serialize the data as a JavaScript array. In my current situation, my JavaScript is isolated in a separate .js file where Razor can't follow so using JsonConvert.SerializeObject wasn't an option.

Definitely an odd bit of functionality here. It would be great if anyone has some insight as to why JSON serialization reacts the way by default; bug or intentional?

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74899

Convert it to a list of key value pairs before passing to the JSON serializer:

JsonConvert.SerializeObject(new List<KeyValuePair<string,string>>(dictionary));

Upvotes: 4

Related Questions