使用.Net反序列化JSON中的动态类型

时间:2011-03-31 23:19:36

标签: .net json dynamic

我有以下JSON:

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

我使用以下类将其反序列化为.net:

[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;
    }

问题是,反序列化为ByType类的类型实际上是动态的,因此可以更改。如何在不知道类型(fulltime,parttime,sub)的情况下反序列化此JSON。我尝试在“Counts”类中执行此操作,但它不起作用:

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

1 个答案:

答案 0 :(得分:1)

查看此答案,链接讨论与您的需求一致。关键是新的dynamic类型:

Deserialize JSON into C# dynamic object?