George Fordham
George Fordham

Reputation: 31

Deserializing a dynamic type in JSON with .Net

I have the following JSON:

\"success\":true,
   \"requestSecs\":0.084988117218,
   \"body\":{
      \"countsByStatus\":[
         {
            \"status\":\"yes\",
            \"counts\":{
               \"byType\":{
                  \"fulltime\":0,
                  \"parttime\":0,
                  \"sub\":0,
               },
               \"total\":0
            }
         }

I am deserializing this into .net with the following classes:

[DataContract]
    public class ResponseAttendanceList
    {
        [DataMember(Name = "success")]
        public string Success;

        [DataMember(Name = "requestSecs")]
        public string RequestSecs;

        [DataMember(Name = "body")]
        public AttendanceList AttendanceList;
    }

[DataContract]
    public class AttendanceList
    {
        [DataMember(Name = "countsByStatus")]
        public List<Status> countsByStatus;        
    }

[DataContract]
    public class Status
    {
        [DataMember(Name = "status")]
        public string status;

        [DataMember(Name = "counts")]
        public Counts counts;
    }

[DataContract]
    public class Counts
    {
        [DataMember(Name = "byType")]
        public ByType byType;

    }

[DataContract]
    public class ByType
    {
        [DataMember(Name = "fulltime")]
        public int fulltime;

        [DataMember(Name = "parttime")]
        public int parttime;

        [DataMember(Name = "sub")]
        public int sub;
    }

The problem is, the types deserialized into the ByType class are actually dynamic, so can change. How do I deserialize this JSON without knowing the types (fulltime, parttime, sub). I tried to do this on the “Counts” class, but it didn’t work:

    [DataContract]
    public class Counts
    {        
        [DataMember(Name = "byType")]
        public KeyValuePair<string, int> byType;     
    }

Upvotes: 3

Views: 3716

Answers (1)

Milimetric
Milimetric

Reputation: 13549

Check out this answer, the linked-to discussion is along the lines of what you need. The key is the new dynamic type:

Deserialize JSON into C# dynamic object?

Upvotes: 1

Related Questions