2014-01-08 65 views
-1

我收到錯誤解析JSON成JArray

「的類型 'System.Reflection.TargetInvocationException' 未處理的異常出現在 System.Windows.ni.dll」

當我嘗試解析Json數據。

MessageBox.Show(e.Result); 
JArray a = JArray.Parse(e.Result); 

完整的錯誤

Error: 
Newtonsoft.Json,JsonReaderException: Error reading JArray from JsonReader. 
Current JsonReader item is not an array: StartObject. Path ", line 1,posistion 1. 
at 
Newtonsoft.Json.Linq.JArray.Load(JsonReader reader) 
at 
Newtonsoft.Json.Linq.JArray.Parse(String json) 
at 
GameStatsTrack.MainPage.dota_DownloadStringCompleted(Object senders, DownloadStringCompletedEventArgs e) 

當I輸出它使用消息框,但是當我嘗試使用JArray它導致程序扔JSON數據正在顯示上面的錯誤。

{ 
    "result": { 
     "status": 1, 
     "num_results": 1, 
     "total_results": 500, 
     "results_remaining": 499, 
     "matches": [ 
      { 
       "match_id": 460632360, 
       "match_seq_num": 419390537, 
       "start_time": 1389202765, 
       "lobby_type": 7, 
       "players": [ 
        { 
         "account_id": 52194129, 
         "player_slot": 0, 
         "hero_id": 51 
        }, 
        { 
         "account_id": 121480884, 
         "player_slot": 1, 
         "hero_id": 74 
        }, 
        { 
         "account_id": 115633024, 
         "player_slot": 2, 
         "hero_id": 54 
        }, 
        { 
         "account_id": 4294967295, 
         "player_slot": 3, 
         "hero_id": 47 
        }, 
        { 
         "account_id": 106189937, 
         "player_slot": 4, 
         "hero_id": 5 
        }, 
        { 
         "account_id": 4294967295, 
         "player_slot": 128, 
         "hero_id": 30 
        }, 
        { 
         "account_id": 4294967295, 
         "player_slot": 129, 
         "hero_id": 89 
        }, 
        { 
         "account_id": 4294967295, 
         "player_slot": 130, 
         "hero_id": 25 
        }, 
        { 
         "account_id": 113052377, 
         "player_slot": 131, 
         "hero_id": 88 
        }, 
        { 
         "account_id": 4294967295, 
         "player_slot": 132, 
         "hero_id": 48 
        } 
       ] 
      } 
     ] 
    } 
} 
+0

你可以分享JSON數據嗎?用你提供的信息很難分辨。也;拋出異常的InnerException是什麼?看起來可能存在反思問題,但同樣很難說。 –

+0

@Duncan請編輯你的問題,並顯示完整的例外,以允許他人來幫助你。 – geedubb

+0

編輯我的帖子以顯示JSON數據。它來自蒸汽API,Dota匹配歷史。 – Duncan

回答

0

由於您使用的是Json.Net。您可以使用服務,例如http://json2csharp.com/來生成可以反序列化的DTO對象。這樣做後,你會得到幾個班,其中一個叫RootObject。您可以將其重命名爲任何您想要的內容。然後,您可以執行如下操作:

var dtoObj = JsonConvert.DeserializeObject<RootObject>(response); 

其中響應是Json字符串格式。此方法將爲您提供DTO對象的優點,而不是處理JArray。要訪問您的數據,它將是dtoObj.Result.Matches

您的其他選擇是使用dynamic

var dynObj = JsonConvert.DeserializeObject<dynamic>(response); 

動態的好處是你不必維護DTO對象,但是你會失去一些強制的鍵入和結構。但動態時,您可以通過dynObj.result.matches訪問匹配項。有時用dynamic你必須明確地將它轉換成某種Enumerable,這很煩人,所以我更喜歡上面的DTO方法。