randoms
randoms

Reputation: 2783

list to json object using json.net

I am using json.net to convert currency rates to json.

The C# entity got a Name and a Value, where Name is USD, GBP and so one, and Value the currencyrate.

I don't know the index of the different currencies, so in javascript I want to get a currency by saying var a = obj["USD"]; insead of looping through an array and find array[i].name == "USD". The default output of JsonConvert.SerializeObject(currencyList); is:

[
    {"name": "one",   "pId": "foo1", "cId": "bar1"},
    {"name": "two",   "pId": "foo2", "cId": "bar2"},
    {"name": "three", "pId": "foo3", "cId": "bar3"}
]

I would however like something like:

{
    "one":   {"pId": "foo1", "cId": "bar1"},
    "two":   {"pId": "foo2", "cId": "bar2"},
    "three": {"pId": "foo3", "cId": "bar3"}
}

Is this possible to acheieve with json.net, or do i need to write my own parser?

Upvotes: 2

Views: 541

Answers (1)

Yogu
Yogu

Reputation: 9445

You have to create a dictionary:

Dictionary<String, DataType> dictionary = list.ToDictionary(d => d.name);

Replace DataType by the type of your entity.

Then, you can serialize the dictionary using json.

Upvotes: 3

Related Questions