尝试反序列化JSON时获取NullReferenceException

时间:2017-07-19 12:31:27

标签: c# serialization

所以我试图围绕如何正确地反序列化这个问题。

{
  "_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结构。

任何帮助将不胜感激

编辑:修正了拼写错误

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:0)

编辑:

你可以完全消除一个课程 - 我真诚地将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,你可以接受另一个答案。

相关问题