2017-07-19 33 views
3

因此我試圖圍繞如何正確地反序列化我的頭。嘗試反序列化JSON時獲取NullReferenceException

{ 
    "_note": "You are currently authenticated with the API using your OPSkins login session cookies.", 
    "status": 1, 
    "time": 1500460072, 
    "response": { 
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": { 
     "op_7_day": 999, 
     "op_30_day": 932 
    }, 
    "AK-47 | Aquamarine Revenge (Factory New)": { 
     "op_7_day": 2738, 
     "op_30_day": 2665 
    } 
    } 
} 

這裏是我的階級結構

public class OpRoot 
{ 
    public string _note { get; set; } 
    public int status { get; set; } 
    public int time { get; set; } 
    public OpResponse response { get; set; } 
} 

public class OpResponse 
{ 
    public Dictionary<string, OpItem> items { get; set; } 
} 

public class OpItem 
{ 
    public int op_7_day { get; set; } 
    public int op_30_day { get; set; } 
} 

這是我正在嘗試反序列化:

OpRoot OpInstance = JsonConvert.DeserializeObject<OpRoot>(readerResponse); 

我試圖改變字典轉爲列表,而不是,而是嘗試調用「項目」對象時得到了相同的結果「System.NullReferenceException」:

Console.WriteLine(OpInstance.response.items.Values); 

所以我認爲問題在於「OpResponse」類的代碼。大部分代碼之前都有效,但是使用另一種JSON結構。

任何幫助,將不勝感激

編輯:固定錯字

+2

JSON格式不正確,Json始終以'{' –

+0

'開頭,您的JSON格式不正確。檢查大括號({})的位置。 –

+0

這是帖子中的錯字,現在修復了。 – multikus

回答

2

你不需要OpResponse。以下類應該工作:

public class OpRoot 
{ 
    public string _note { get; set; } 
    public int status { get; set; } 
    public int time { get; set; } 
    public Dictionary<string, OpItem> response { get; set; } 
} 

public class OpItem 
{ 
    public int op_7_day { get; set; } 
    public int op_30_day { get; set; } 
} 
+0

謝謝!奇蹟般有效 – multikus

0

編輯:

可以消除一個類entirely-我會老老實實存儲OpItem有自己的字符串名稱,不過這只是我:

public class OpRoot 
{ 
    public string _note { get; set; } 
    public int status { get; set; } 
    public int time { get; set; } 
    public List<OpItem> {get; set;} 
} 

public class OpItem 
{ 
    public int op_7_day { get; set; } 
    public int op_30_day { get; set; } 
    public string name {get; set;} 
} 

或者,如果你不能改變你得到的json,你可以採取其他的答案。

+0

我將此問題標記爲印刷錯誤,除非這不能解決問題。 – Ares

+0

我的錯!我在這裏發佈的JSON是從一個更長的JSON中截取的,我無意中在這篇文章中忘記了包含這兩個括號。現在修復了錯字,並且錯誤仍然發生 – multikus

+0

我沒有在您的json中看到任何明確命名爲「items」的東西,爲什麼? – Ares