Search code examples
c#jsonjson.netdeserialization

deserializing dynamic named JSON attributes to a C# class


{
  "Documents": {
    "c97bba6f-c8ab-4453-91f8-f663f478910c": {
      "id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
      "name": "name",
      "sys": {
        "c67bfa6f-c8ab-4453-91f8-f663f478910c": {
          "id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
          "name": "sys name"
        },
        "a67bfa6f-c8ab-4453-91f8-f663f478910c": {
          "id": " a67bfa6f-c8ab-4453-91f8-f663f478910c",
          "name": "sys name"
        }
      }
    },
    "f97bba6f-c8ab-4453-91f8-f663f478910c": {
      "id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
      "name": "OZL - B - MECH - AC - Fan Coil Units",
      "sys": {}
    }
  }
}

I've got JSON data in the form above and am having trouble deserializing this into a C# class. The trouble I'm having is that the GUID is used to define the object that the Documents object has rather than the documents object having a list of documents.

I've tried to create a documents object that has a list of object in it and deserialise into this using Newtonsoft. I've also tried a dictionary of string, object in the documents object. None of these work.

Any input or ideas would be most appreciated.

Edit: the biggest issue I'm having is the nesting of Dictionary<GUID, object>. Newtonsoft won't map to the dictionary within the first object. Here's what I have:

public class Documents {
   public dictionary<Guid, System> data { get; set; }
}

public class System {
   public Guid Id { get; set;}
   public string Name { get; set; }
   public dictionary<guid, someOtherobject> otherData { get; set;}
}

Solution

  • Based on your JSON, the class structure you need is this:

    public class RootObject
    {
        public Dictionary<Guid, Document> Documents { get; set; }
    }
    
    public class Document
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Dictionary<Guid, Sys> Sys { get; set; }
    }
    
    public class Sys
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
    

    Then deserialize into the RootObject class like this:

    var root = JsonConvert.DeserializeObject<RootObject>(json);
    

    Here is a working demo: https://dotnetfiddle.net/Uycomw