multikus
multikus

Reputation: 33

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'm trying to deserialize it:

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

I have tried to change the Dictionary into a List instead, but got the same result "System.NullReferenceException" when trying to call the "items" object:

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

So I think the problem lies within the code of the "OpResponse" class. Most of this code has worked before, however with another JSON structure.

Any help would be appreciated

EDIT: Fixed typo

Upvotes: 3

Views: 362

Answers (2)

Athena
Athena

Reputation: 3228

EDIT:

You can eliminate one class entirely- I'd honestly store OpItem with its 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 can't change the json you get, you could take the other answer.

Upvotes: 0

fknx
fknx

Reputation: 1785

You don't need the OpResponse. With the following classes it should work:

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

Upvotes: 2

Related Questions