Home > front end >  how to deserialize json into dictionary c# and define the key?
how to deserialize json into dictionary c# and define the key?

Time:01-28

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.

CodePudding user response:

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)

CodePudding user response:

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

  •  Tags:  
  • Related