Home > OS >  How to load data from distinct .json file to List<T>, C#?
How to load data from distinct .json file to List<T>, C#?

Time:11-21

My problem is that I want to take data from .json file, and initialize with it a list of objects.

I have my .json file:

{
  "Card1": {
    "Name": "Kyiv",
    "price": 200,
    "taxes": 150
  },
  "Card2": {
    "Name": "Kamiyanske",
    "price": 150,
    "taxes": 100
  },
  "Card3": {
    "Name": "Rivne",
    "price": 150,
    "taxes": 100
  }
}

I want to take this data and fill in objects, and create a list of them

This is my try to do so

            List<Card> LoadJson()
            {
                using (StreamReader r = new StreamReader("C:\\fileName.json"))
                {
                    string json = r.ReadToEnd();
                    var items = JsonConvert.DeserializeObject<List<Card>>(json);
                    return items;
                }
            }

            var Cards = LoadJson();
            Console.WriteLine(Cards[0].Name);

But every time I get an exception:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WpfApp1.Card]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3])

thank you in advance

CodePudding user response:

As a matter of fact you have a json object that fits a Dictionary, not a List. You can parse json and convert it to list in one line

List<Card> items = JObject.Parse(json).Properties().Select(jo =>jo.Value.ToObject<Card>() ).ToList();

CodePudding user response:

It's a very practical question and I actually had this kind of json payload at work.

I use dynamic object to process the payload as below,

           using (StreamReader r = new StreamReader("C:\\fileName.json"))
           {
                string json = r.ReadToEnd();
                dynamic items = JsonConvert.DeserializeObject(json);

                List<Card> cards = new List<Card>();

                foreach(var item in items)
                {
                    var jsonString = JsonConvert.SerializeObject(item.Value);
                    Card card = JsonConvert.DeserializeObject<Card>(jsonString);
                    cards.Add(card);
                }

                return cards;
            }
  • Related