Search code examples
c#jsonjson.netdeserialization

JSON Deserialize to list C#


My JSON has this information:

[
 {
  "era_1":{"technology_cost":"10000"},
  "era_2":{"technology_cost":"15000"},
  "era_3":{"technology_cost":"20000"},
  "era_4":{"technology_cost":"25000"},
  "era_5":{"technology_cost":"30000"}
 }
]

I want to do:

EraData = JsonConvert.DeserializeObject<List<ClassEra>>(JSON);

Being ClassEra

public class ClassEra
{
    public string name { get; set; }
    public string technology_cost { get; set; }
}

And obviously it doesn't work.

I don't understand the type of data that is coming out of the deserializer.

By the way I'm using Newtonsoft.


Solution

  • try this one

    EraData  = JsonConvert.DeserializeObject<List<Dictionary<string, ClassEra>>>(JSON);
    

    And class will be

        public class ClassEra
        {
            public string technology_cost { get; set; }
        }
    

    Fetching details

    I prefer to use dictionary because time complexity of fetching value is O(1) by key like dic[key]

    //By this :- get complete dictionary
    var dic = EraData[0]; //and iterate by foreach loop 
     
    //by this you can get all technology cost:- 
    var technology_cost = EraData.SelectMany(x => x.Values);
    

    Screenshots

    Dictionary enter image description here

    Technology Cost enter image description here