在尝试反序列化JSON时出现NullReferenceException错误

3

我正在尝试理解如何正确反序列化这个对象。

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

我尝试将字典转换为列表,但在尝试调用“items”对象时仍然出现了“System.NullReferenceException”的相同结果。
Console.WriteLine(OpInstance.response.items.Values);

所以我认为问题在于“OpResponse”类的代码。大部分代码之前都可以使用,但是使用另一种JSON结构时出现了问题。

希望能得到任何帮助。

编辑:修正了拼写错误。


2
JSON格式不正确,Json始终以{开头。 - Christoph K
你的JSON格式不正确。请检查大括号({})的位置。 - Dalvinder Singh
这是帖子中的一个笔误,现在已经修正了。 - multikus
2个回答

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

编辑:

你可以完全消除一个类 - 我会诚实地将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,则可以采用其他答案。


我将此问题标记为排版错误,除非这不能解决问题。 - Athena
我的错!我在这里发布的JSON是从一个更长的JSON中剪切出来的,我不小心忘记在这篇文章中包含两个括号。现在已经修复了这个错误,但错误仍然存在。 - multikus
我在你的JSON中没有看到任何明确命名为“items”的内容,这是为什么? - Athena
如果你把它们存储为列表,那么在 JSON 格式方面,对你来说会更容易。除非你有数十亿个,否则列表就可以胜任,并且它会让你的 JSON 稍微简单一些。 - Athena

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接