将包含不同数量参数的JSON数据反序列化为C#(使用Json.NET)

时间:2012-11-07 08:49:59

标签: c# json rest json.net

我正在尝试反序列化以下JSON响应:

[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]

然而,问题出现在“类别”之后的参数数量可以从0到10之间变化。这意味着以下所有可能的JSON响应:

[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Bad", "1":"OK", "2":"Good", "3":"Very good"} … ]

我正在对以下形式的对象进行反序列化:

class Poll
    {
        public int pollid { get; set; }
        public string question { get; set; }
        public DateTime start { get; set; }
        public DateTime end { get; set; }
        public string category { get; set; }

        [JsonProperty("0")]
        public string polloption0 { get; set; }
        [JsonProperty("1")]
        public string polloption1 { get; set; }
        [JsonProperty("2")]
        public string polloption2 { get; set; }
        [JsonProperty("3")]
        public string polloption3 { get; set; }
        [JsonProperty("4")]
        public string polloption4 { get; set; }
        [JsonProperty("5")]
        public string polloption5 { get; set; }
        [JsonProperty("6")]
        public string polloption6 { get; set; }
        [JsonProperty("7")]
        public string polloption7 { get; set; }
        [JsonProperty("8")]
        public string polloption8 { get; set; }
        [JsonProperty("9")]
        public string polloption9 { get; set; }
    }

我的问题是:是否有更好的方法来处理存储不同数量的参数?有10个类属性可能会或可能不会使用(取决于响应)似乎是这样的“黑客”。

真正感谢任何帮助!

非常感谢, 泰德

2 个答案:

答案 0 :(得分:0)

您可以在和Array

中保存可变数量的属性

有像

这样的东西
List<string> ();

你把所有的polloption1,polloption2 ......

放在哪里

或者您可以将json反序列化为动态类型

dynamic d = JObject.Parse(json);

并访问您知道存在的属性

d.pollid, d.start, d.category ... 

答案 1 :(得分:0)

  

是否有更好的方法来处理存储不同数量的参数?

您可以反序列化为ExpandoObjectdynamic,例如

var serializer = new JavaScriptSerializer();   
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
    Console.WriteLine(item["question"]);
}