Getting NullReferenceException when trying to deserialize JSON

so I'm trying to wrap my head around how to deserialize this properly.

{
  "_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
    }
  }
}

      

Here is my class structure

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; }
}

      

This is how I try to deserialize it:

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

      

I tried changing the dictionary in the list instead, but got the same "System.NullReferenceException" result when trying to call the "items" object:

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

      

So, I think the problem lies in the code of the OpResponse class. Most of this code worked before, however with a different JSON structure.

Any help would be appreciated

EDIT: typo fixed

+3


source to share


2 answers


You don't need it OpResponse

. It should work with the following classes:



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; }
}

      

+2


source


EDIT:

You can exclude one class entirely - I'd honestly keep OpItem

with my own string name, but that's just me:



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;}
}

      

Or, if you cannot change the json you have, you can take a different answer.

0


source







All Articles