2015-11-12 152 views
0

我需要在C#中解析JSON的幫助。有我的JSON字符串,我正試圖分析和處理。我不想創建一個類實例化對象,因爲可以有更多的呼叫有很多返回的對象類型 - 錦標賽,團隊,用戶等C#JSON反序列化字典異常

{ 
    "response":{ 
     "2":{ 
      "tournament_id":2, 
      "created_at":{ 
       "date":"2015-11-09 21:01:06", 
       "timezone_type":3, 
       "timezone":"Europe/Prague" 
      }, 
      "creator_id":1, 
      "name":"Tournament Test #1", 
      "desc":"...!", 
      "state":0, 
      "is_visible":1 
     }, 
     "3":{ 
      "tournament_id":3, 
      "created_at":{ 
       "date":"2015-11-09 21:01:06", 
       "timezone_type":3, 
       "timezone":"Europe/Prague" 
      }, 
      "creator_id":1, 
      "name":"Tournament Test #2", 
      "desc":"...", 
      "state":1, 
      "is_visible":1 
     } 
    }, 
    "error":false 
} 

我使用JSON.net庫解析JSON字符串,這是我使用我的程序C#代碼:

public class API 
    { 
     private WebClient client; 

     protected string auth_key = "xxx"; 
     protected string base_url = "http://127.0.0.1/tournaments_api/www/"; 
     private string endpoint_url = ""; 
     private string url_params = ""; 

     public string url_data; 
     public Dictionary<string, string>[] data; 

     public bool success = false; 
     public string errorMessage = ""; 
     public int errorCode = 0; 

     public API() 
     { 
      this.client = new WebClient(); 
     } 

     private void Request() 
     { 

      string url = this.base_url + this.endpoint_url + "/" + this.auth_key + "?" + this.url_params; 
      this.url_data = this.client.DownloadString(url); 
      Console.WriteLine(this.url_data); 

      this.data = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(this.url_data); 
     } 
    } 

有這個問題解析:

類型的未處理的異常「Newtonsoft.Json.JsonSerializationEx ception'發生在 Newtonsoft.Json.dll

附加信息:無法反序列化當前的JSON對象 (例如,因爲這個類型需要一個JSON數組(例如[1,2,...,0,{「name」:「value」}),因此類型爲 'System.Collections.Generic.Dictionary`2 [System.String,System.String] []' ' 3])正確地反序列化 。

要修復此錯誤,請將JSON更改爲JSON數組(例如 [1,2,3])或更改反序列化類型,以使其成爲正常的.NET 類型(例如,不是整數類型的基本類型,而不是類似數組或列表的集合類型 ),它們可以從JSON對象反序列化。 也可以將JsonObjectAttribute添加到該類型中,以強制它從一個JSON對象反序列化爲 。

路徑 '響應',1號線,位置12

感謝您的幫助! :)

+0

你的JSON中絕對沒有數組。 –

回答

0

您的JSON是一個對象,在C#中可以反序列化爲Dictionary<string, object>。但是,您嘗試將其反序列化爲數組,而絕對沒有數組。

您需要將此更改爲:

public Dictionary<string, object>[] data; 

// ... 

JsonConvert.DeserializeObject<Dictionary<string, object>>(this.url_data); 

同時,即使改變之後,你將不能訪問嵌套對象。

當你寫的

我不想創建一個類實例化對象,因爲可以有更多的呼叫有很多返回的對象類型 - 錦標賽,團隊,用戶等

我可能會建議使用dynamic

dynamic data = JsonConvert.DeserializeObject(this.url_data); 

然後,你就可以用它來工作,像動態對象:

var err = data.error; 

同時,創建一個類來描述這個模型並用於反序列化這個JSON聽起來對我更好。

+0

哦哇,動態..:D謝謝! – TheKronnY

0

替代Yeldar Kurmangaliyev的答案是使用內置的LINQ to JSON支持JSON.NET庫:

JObject jObject = JObject.Parse("-- JSON STRING --"); 

JToken response = jObject["response"]; 

bool error = jObject["error"].Value<bool>(); 

有很多的擴展方法,允許JSON字符串容易解析。