2017-04-20 24 views
0

winforms用に設計されたgithubからコードを変換しようとしていますが、次のエラーが発生しています。json応答オブジェクトでWeb APIエラーが発生しました

//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)

エラーがオブジェクトのインスタンスに設定されていない

オブジェクト参照です。 説明:現在のWeb要求の実行中に、未処理の例外が発生しました。エラーの詳細とコード内のどこで発生したのかについては、スタックトレースを参照してください。 例外の詳細:System.NullReferenceException:オブジェクト参照がオブジェクトのインスタンスに設定されていません。

ソースエラー:

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() 

今、私は、これは通常、オブジェクトがintitiatedされていない場合であるが、VARノードが動かないことを知っていますか?

大変助かります。私はセキュリティのために私のAPIキーを編集するが、それは過去にうまくいく。

+0

編集時にsm4に感謝してマークダウンに慣れることがあります –

答えて

0

キーワードvarは、残りのステートメントから変数の型を推論するようにコンパイラに指示します。この場合、JsonConvert.DeserializeObject<dynamic>を使用してストリームを逆シリアル化しようとしているため、推定される型はdynamicになります。しかし、それは変数の値がnullでないことを保証するものではありません!実際に、レスポンスストリームにデータがない場合、JsonConvert.DeserializeObjectになります。確かにを返します。したがって、ヌルであるオブジェクトのプロパティを参照しようとすると、例外がスローされます。これはここで起こっていることとまったく同じです。

私が推測しているのは、期待している応答ではなく、サーバーから何らかのエラーが戻ってきているということです。あなたのコードは、私が見ることができるHTTPエラーをチェックしません。それが成功したと仮定して、盲目的に応答を処理しようとします。サーバーから実際に何を取得しているのかを調べるには、FiddlerのようなWebデバッグプロキシを使用する必要があります。次に、適切なエラー処理とヌルチェックを使用してコードを強化する必要があります。詳細については、What is a NullReferenceException, and how do I fix it?を参照してください。

関連する問題