APIからJSONデータを取得するC#コードがあります。JSONを逆シリアル化してDataGridViewに結果を表示しようとすると例外が発生する
{
"count": 32696,
"results": [{
"data_id": 0,
"name": "Extended Potion of Ghost Slaying",
"rarity": 0,
"restriction_level": 0,
"img": "",
"type_id": 0,
"sub_type_id": 0,
"price_last_changed": "2013-03-18 17:00:31 UTC",
"max_offer_unit_price": 0,
"min_sale_unit_price": 0,
"offer_availability": 0,
"sale_availability": 0,
"sale_price_change_last_hour": 0,
"offer_price_change_last_hour": 0
}]
}
(結果でただ一つの項目以上ががあります。)
私はこのような2つのクラス作っています:
internal class MyClass
{
public int data_id { get; set; }
public string name { get; set; }
public int rarity { get; set; }
public int restriction_level { get; set; }
public string img { get; set; }
public int type_id { get; set; }
public int sub_type_id { get; set; }
public string price_last_changed { get; set; }
public int max_offer_unit_price { get; set; }
public int min_sale_unit_price { get; set; }
public int offer_availability { get; set; }
public int sale_availability { get; set; }
public int sale_price_change_last_hour { get; set; }
public int offer_price_change_last_hour { get; set; }
}
internal class RootObject
{
public int count { get; set; }
public List<MyClass> results { get; set; }
}
をそしてここでJSONは次のようになります
using (WebClient wc = new WebClient())
{
string URI = "a good url";
wc.Headers.Add("Content-Type", "text");
string HtmlResult = wc.DownloadString(URI);
MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(HtmlResult);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(HtmlResult, (typeof(DataTable)));
this.dataGridView1.DataSource = dt;
}
をしかし、私はこのコードを実行すると、私はエラーを取得する:私はJSONを取得し、それをデシリアライズ一部
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'gwspiderv2.MyClass[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
私はすでにこのタイプのコードを別のAPIでエラーなく使用しています。私は間違って何をしていますか?
うん、あなたが持っているJSON 1(1)オブジェクトのために、それ自体ではなく、配列で、ちょうどその中括弧でそこに座って。角かっこの間ですか?いいえ、ちがいます。 JSONでは、配列は角かっこで囲まれたオブジェクトまたは値のコンマ区切りのシーケンスです。あなたはデシリアライザに配列を逆シリアル化するように指示しています - 配列に対して* insist *するように指示しています。そこで配列を探します。代わりに、あなたはそれを与えたものを見つけます。つまり、これは配列ではありません。 –
生のJSONの外観はどうですか?エラーに基づいて、配列ではなくJSONオブジェクトでなければなりません。たぶんJSONをあなたが使用していない 'RootObject'型に逆シリアル化することを意図していましたか? – dbc
jsonは次のようになります:{count}:32696、 "results":[{"data_id":0、 "name": "Ghost Slayingの拡張ポーション"、 "希少度:0"、 "restriction_level" 0、 "sub_ type_id":0、 "price_last_changed": "2013-03-18 17:00:31 UTC"、 "max_offer_unit_price":0、 "min_sale_unit_price":0、 "offer_availability "0:" sale_availability ":0、" sale_price_change_last_hour ":0、" offer_price_change_last_hour ":0}、{" data_id ":1、" name ":" MONSTER ONLY Moa Unarmed *など... – Helmuteke