user2354274
user2354274

Reputation: 187

Parsing json to generic list in C#

I have Json Like value name pair. I need to convert to Generic list.

{ "options": { "32": "S", "4": "SM", "33": "M", "34": "L", "35": "XL", "37": "XXL", "38": "XXXL" } }

My class like

public class Options
{
    public int optionId { get; set; }
    public string OptionName { get; set; }
}

How to convert json to List<Options>

Upvotes: 0

Views: 499

Answers (1)

sa-es-ir
sa-es-ir

Reputation: 5042

First convert your json to Dictionary<string, string> and then convert it to your model like this:

  public class OptionDictionary
    {
        public Dictionary<string, string> Options { get; set; }
    }
    public class Options
    {
        public int OptionId { get; set; }
        public string OptionName { get; set; }
    }
  
  var list = JsonConvert.DeserializeObject<OptionDictionary>(json).Options.Select(x=>new Options(){OptionId = int.Parse(x.Key), OptionName = x.Value}).ToList();

Upvotes: 2

Related Questions