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.