Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
corbinyo opened this issue Sep 2, 2020 · 1 comment

Comments

@corbinyo
Copy link

corbinyo commented Sep 2, 2020

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
Copy link

gep13 commented Sep 2, 2020

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants