簡體   English   中英

嘗試反序列化JSON時獲取NullReferenceException

[英]Getting NullReferenceException when trying to deserialize JSON

所以我試圖圍繞如何正確地反序列化這個問題。

{
  "_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);

我試圖將Dictionary更改為List,但在嘗試調用“items”對象時得到了相同的結果“System.NullReferenceException”:

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

所以我認為問題在於“OpResponse”類的代碼。 大多數此代碼以前都有用,但是使用了另一種JSON結構。

任何幫助,將不勝感激

編輯:修正了拼寫錯誤

您不需要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; }
}

編輯:

你可以完全消除一個類 - 我誠實地用自己的字符串名稱存儲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,你可以采取另一個答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM