user7280961
user7280961

Reputation:

Object deserialization error

Here is my json format :

{
  "groupe1": [
    {
      "nom": "tache1",
      "type": "Tache"
    },
    {
      "nom": "tache2",
      "type": "Tache"
    }
  ],...
}

I want to deserialize this into these classes, Groupe and Item. My code :

public static class Config
{
    public const string pathSharedFile = @"Config.json";

    public static List<string> ReadGroupes()
    {
        StreamReader sr = new StreamReader(pathSharedFile);
        List<Groupe> Groupes = JsonConvert.DeserializeObject<List<Groupe>>(sr.ReadToEnd());
        return new List<string>();
    }
}

public class Groupe
{
    public Item[] items { get; set; }
}
public class Item
{
    public string nom { get; set; }
    public string type { get; set; }
}

An error is thrown when I try the cast. Can someone help me ?

Upvotes: 0

Views: 56

Answers (1)

Gusman
Gusman

Reputation: 15151

Remove the Groupe class and use a dictionary like this:

Dictionary<string, Item[]> Groupes = 
          JsonConvert.DeserializeObject<Dictionary<string, Item[]>>(sr.ReadToEnd());

As the properties are dynamic using a dictionary will allow you to access each group by key:

var groupContent = Groupes["groupe1"];

foreach(var item in groupContent)
   //Do whatever you want with the item

Upvotes: 2

Related Questions