LitJSON / litjson

JSON library for the .Net framework
https://litjson.net/
Other
1.36k stars 403 forks source link

NullReferenceException: Object reference not set to an instance of an object If value is Null #122

Open corbinyo opened 4 years ago

corbinyo commented 4 years ago

When using:

public JsonData itemData;

itemData = JsonMapper.ToObject("[" + myjson.text.Trim() + "]");

 void ConstructItemDatabase()
        {
            for (int i = 0; i < itemData[0]["listings"].Count; i++)
            { 
                Debug.Log("Count all the listings FOR BROWSE : " + itemData);

                Debug.Log("log" + itemData[0]["listings"][i]["name"]);

                Debug.Log("token" + itemData[0]["listings"][i]["token"]);

                Debug.Log("SID" + itemData[0]["listings"][i]["sequenceId"]);

                Debug.Log("thumbnail" + itemData[0]["listings"][i]["thumbnailImageUrl"]);

                database.Add(new Art(
                (int)itemData[0]["listings"][i]["sequenceId"],
                (int)itemData[0]["listings"][i]["artId"],
                itemData[0]["listings"][i]["token"].ToString(),
                itemData[0]["listings"][i]["name"].ToString(),
                itemData[0]["listings"][i]["thumbnailImageUrl"].ToString()));
            }
        }
    }

with the Json:

{
  "searchId": null,
  "listings": [
    {
      "sequenceId": 0,
      "artId": 75,
      "token": null,
      "name": "Frank",
      "thumbnailImageUrl": "https://imymages/1.jpg"
    },
    {
      "sequenceId": 1,
      "artId": 15,
      "token": "null",
      "name": "peep",
      "thumbnailImageUrl": "myimages/2.jpg"
    }
  ]

The Null value from "Token" from the 1st listing object returns NullReferenceException: Object reference not set to an instance of an object

Why Can I not have null values?

gep13 commented 4 years ago

@corbinyo you can have null values, and you can see that as you step through the code that you have:

image

However, since this is possible, you then need to account for the possibility of it being a null value. To that end, you can't then do this:

itemData[0]["listings"][i]["token"].ToString(),

Since calls ToString() on a null object will result in a Null Reference Exception.