c# - 尝试反序列化 JSON 时获取 NullReferenceException

标签 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 结构。

任何帮助将不胜感激

编辑:修复错字

最佳答案

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

关于c# - 尝试反序列化 JSON 时获取 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190695/

相关文章:

c# - 将 javascript 函数转换为 C#(转换问题)

c# - 将 RelativePanel 的子项的尺寸设置为与父 View 的尺寸成比例

c# - 在 SQLCe 数据库中存储对象的最有效方法是什么?

Java 序列化方法

c# - 如果进程以编程方式运行(来自 C#),则“没有这样的文件或目录”

java - 如何覆盖通用存储库错误消息

c# - 对 asp.net mvc 应用程序的长轮询需要 POST 而不是 GET ajax 方法。为什么?

c# - 反序列化 MemoryStream - 意外行为

c++ - 从基类发送和接收序列化类

c# - 在 .NET Framework 2 和 4 中进行序列化和反序列化 - C#