1

我正在尝试反序列化以下 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 个可能使用或不使用的类属性(取决于响应)似乎是这样的“黑客”。

任何帮助将不胜感激!

非常感谢,特德

4

2 回答 2

0

您可以在 Array 中保存可变数量的属性

有类似的东西

List<string> ();

你把所有 polloption1, polloption2 ...

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

dynamic d = JObject.Parse(json);

并访问您知道存在的属性

d.pollid, d.start, d.category ... 
于 2012-11-07T08:54:48.373 回答
0

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

您可以反序列化为ExpandoObjectdynamic例如

var serializer = new JavaScriptSerializer();   
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
    Console.WriteLine(item["question"]);
}
于 2012-11-07T08:55:38.900 回答