Search code examples
c#jsondictionaryjsonconvert

how to deserialize json into dictionary c# and define the key?


I have this class:

    public class Campaign{
     public   int campaign_id { get; set; }
     public   string campaign_name { get; set; }
     public   int representative_id { get; set; }}

And I can deserialize the JSON to a List like this:

 Campaigns = JsonConvert.DeserializeObject<List<Campaign>>(jsonstring);

But I want to access the items base on the campaign_name, how can I do that? How to Deserialize it to a dictionary where the value will be the object and the key will be the campaign_name? Thank you.


Solution

  • You can use the ToDictionary method to convert your List. You can read more at MSDN:

    var dict = Campaigns.ToDictionary(x => x.campaign_id);
    

    Note that this will fail if an item exists in the list multiple times so you can Distinct:

    var dict = Campaigns.Distinct().ToDictionary(x => x.campaign_id)