'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 1:[1]

For the Dictionary you can go with:

var dictionaryOfCampaign = Campaigns.ToDictionary(x => x.campaign_id, y => y);

If you don't want to use a dictionary you can filter your List using a linq query like this:

var filteredCampaign = Campaigns.Where(x => x.campaign_name.Equals("TEST"));
var filteredCampaign2 = Campaigns.Where(x => x.campaign_name.Contains("TEST"));

Remember to add in your using System.Linq

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1