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

と配列のいずれかに可変数のプロパティを保持できます

のようなものを持っています

List<string> ();

ここに、polloption1、polloption2..のすべてを配置します。

または、jsonを動的タイプに逆シリアル化することもできます

dynamic d = JObject.Parse(json);

そして、あなたが存在することがわかっているプロパティにアクセスします

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

さまざまな数のパラメーターの格納を処理するためのより良い方法はおそらくありますか?

ExpandoObjectまたはdynamicegに逆シリアル化できます

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 に答える