0

I am trying to convert a piece of code from a github that was designed for winforms however I am having the following error.

//Retrieve and set a post code value to a variable.
    var mPostCode = txtPostCode.Text;


    mApiKey = "";

    string url =
      String.Format("http://pcls1.craftyclicks.co.uk/json/basicaddress?postcode={0}&response=data_formatted&key={1}",
          mPostCode, mApiKey);



    //Complete XML HTTP Request
    WebRequest request = WebRequest.Create(url);
    //Complete XML HTTP Response
    WebResponse response = request.GetResponse();

    //Declare and set a stream reader to read the returned XML
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Get the requests json object and convert it to in memory dynamic
    // Note: that you are able to convert to a specific object if required.
    var jsonResponseObject = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());

    // check that there are delivery points
    if (jsonResponseObject.thoroughfare_count > 0)
    {

        //If the node list contains address nodes then move on.
        int i = 0;
        foreach (var node in jsonResponseObject.delivery_points)
        {
            ClsAddress address = new ClsAddress()
            {
                AddressID = i,
                AddressLine1 = node.line_1,
                AddressLine2 = node.line_2,
                County = jsonResponseObject.postal_county,
                PostCode = jsonResponseObject.postcode,
                Town = jsonResponseObject.town 

            };

            addressList.Add(address);
            i++;
        }

        this.LoadAddressListIntoDropDown();
    }

The error is hapening on this line // check that there are delivery points if (jsonResponseObject.thoroughfare_count > 0)

Error is

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 148:                //If the node list contains address nodes then move on.
Line 149:                int i = 0;
Line 150:                foreach (var node in jsonResponseObject.delivery_points)
Line 151:                {
Line 152:                    ClsAddress address = new ClsAddress()

Now I know this is normally when an object is not intitiated but is that not what the var node does?

Any help be greatly appreciated. I obv edit out my api key for security but it does get past sucesfully.

  • thanks sm4 for the edit sometimes getting used to the mark down can be a strugle –  Apr 20 '17 at 22:19

1 Answers1

0

The var keyword tells the compiler to infer the type of the variable from the rest of the statement. In this case, the inferred type will be dynamic because you are trying to deserialize the stream using JsonConvert.DeserializeObject<dynamic>. But that does not guarantee that the value of the variable will not be null! In fact, if your response stream has no data, then JsonConvert.DeserializeObject will definitely return null. So, if you then try to reference a property on an object that is null, it will throw an exception, which seems to be exactly what is happening here.

My guess is you are getting some kind of error back from the server instead of the response you are expecting. Your code doesn't do any checking for HTTP errors that I can see; it just blindly tries to process the response, assuming it is successful. You should use a web debugging proxy like Fiddler to find out what you are actually getting from the server. Then, you should enhance your code with appropriate error handling and null checks. See What is a NullReferenceException, and how do I fix it? for more information.

Community
  • 1
  • 1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300