2017-07-20 101 views
0

我是C#的新手,我想使用NewtonSoft反序列化到API的JSON文件,但它導致我到這個錯誤 Newtonsoft.Json.JsonSerializationException:'無法反序列化當前的JSON數組(例如[1 ,2,3])轉換爲'API.JSonConfiguration.exampleLibrary'類型,因爲類型需要JSON對象(例如{「name」:「value」})才能正確地反序列化。反序列化使用newtonsoft

「要解決此錯誤,請將JSON更改爲JSON對象(例如{」name「:」value「})或將反序列化類型更改爲實現集合接口的數組或類型(例如ICollection,IList )等,其可以從一個JSON數組進行反序列化列表。JsonArrayAttribute也可以添加到該類型迫使它從JSON數組反序列化。

路徑「」,第1行,位置1」'

 string url = @"http://180.232.67.229/api/jfiller"; 
     string Data = new WebClient().DownloadString(url 
     exampleLibrary json = JsonConvert.DeserializeObject<exampleLibrary>(Data); 
     MessageBox.Show(json.filler_id); 

示例類庫:

public string filler_id { get; set; } 
    public string filler_title { get; set; } 
    public string filler_type { get; set; } 

JSON

[ 
{ 
    "filler_id":"1", 
    "filler_title":"Star118 E-CarDemo", 
    "filler_type":"1", 
    "filler_file":"Star118CarTeaser‌​1.mp4", 
    "filler_durat‌​ion":"83", 
    "created_a‌​t":"2017-06-10 09:08:41", 
    "updated":"2017-06-10 09:08:41","status":"0" 
    }, 
    { 
    "filler_id":"2", 
    "filler_title":"Sta‌​r118", 
    "filler_type":‌​"2", 
    "filler_file":"S‌​tar118Solar1.PNG", 
    "f‌​iller_duration":"10"‌​, 
    "created_at":"2017-‌​06-10 09:09:26", 
    "updated":"2017-06-10 09:09:26","status":"0" 
    } 
] 
+0

你可以發佈你的JSON字符串嗎? – Xela

+0

[{「filler_id」:「1」,「filler_title」:「Star118 E-CarDemo」,「filler_type」:「1」,「filler_file」:「Star118CarTeaser1.mp4」,「filler_duration」:「83」,「created_at 「:」2017-06-10 09:08:41「,」updated「:」2017-06-10 09:08:41「,」status「:」0「},{」filler_id「:」2「, 「filler_title」:「Star118」,「filler_type」:「2」,「filler_file」:「Star118Solar1.PNG」,「filler_duration」:「10」,「created_at」:「2017-06-10 09:09:26」 ,「updated」:「2017-06-10 09:09:26」,「status」:「0」}] – Ran

+0

你可以嘗試從你的json字符串中刪除「[」&「]」,並把你的json在這裏:json2csharp.com,並解析你的json使用該特定的類 –

回答

0

嘗試

JsonConvert.DeserializeObject<IEnumerable<exampleLibrary>>(Data); 

你有一組數據,但不要在你的JsonConvert或在您的exampleLibrary類(我可以向你發佈的代碼看其指定)。

+0

我得到一個錯誤: System.InvalidCastException:'無法強制類型的對象System.Collections.Generic.List '1 [API.JSonConfiguration.exampleLibrary]'鍵入'API.JSonConfiguration.exampleLibrary'。'當我使用exampleLibrary json =(exampleLibrary)JsonConvert.DeserializeObject >(Data); ,因爲它尋找轉換 – Ran

+0

List json = JsonConvert.DeserializeObject >(Data).ToList();您將返回的對象將是expleLibrary的列表。 – Xela

相關問題