0

The following code is throwing an exception called "Object reference not set to an instance of an object." suggest required changes

public List<WorkspaceRootObject> wrObj=null;
        public RootObject rtObj=new RootObject();
        Hashtable ht = new Hashtable();
        Dictionary<int, Object> d = new Dictionary<int, Object>();
string contextUrl = txtRegServerLocation.Text + "/servlet/rest/v1/contexts";
                    Console.WriteLine("Url is:\n" + contextUrl);
                    HttpWebRequest contextReq = (HttpWebRequest)WebRequest.Create(contextUrl);
                    NetworkCredential ncr = new NetworkCredential("testuser1", "testuser1");
                    CredentialCache creCache = new CredentialCache();
                    creCache.Add(new Uri(contextUrl), "Basic", ncr);
                    contextReq.Credentials = creCache;
                    HttpWebResponse contextRes = (HttpWebResponse)contextReq.GetResponse();
                    Stream str = contextRes.GetResponseStream();
                    StreamReader strReader = new StreamReader(str);
                    string finalContextRes = strReader.ReadToEnd();
                    Console.WriteLine("response is...\n" + finalContextRes);

                    //Deserialzing Json

                     rtObj = JsonConvert.DeserializeObject<RootObject>(finalContextRes);
                    foreach (Item i in rtObj.items)
                    {
                        // Console.WriteLine("{0}",i.id);
                        string curId = i.id;
                        showWorkSpace(curId);
                    }
                    insertRecordInTable();
                    //DataGridViewRow row = new DataGridViewRow();
                    //erverDetails.Rows.Add(imageList1.Images[0], txtRegServerName.Text,txtRegServerLocation.Text);
                }
                else
                {
                    MessageBox.Show("Invalid Url please provide full url");
                }
            }
            catch (WebException ex)
            {
                using (Stream stream = (Stream)ex.Response.GetResponseStream()) 
            {
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
            }

Catch block is throwing this exception System.NullReferenceException was unhandled ?

  • I think the code you pasted is not complete, you need to be also specific on what part throws an exception. – ngeksyo Apr 07 '18 at 13:53
  • Where's the try statement? Anyway presumably when that particular webexception was thrown the Response object is null or there is no response stream to get. Idk step through ot with a debugger. – Mardoxx Apr 07 '18 at 13:55
  • The title say xml serialization but the code is using json. – jdweng Apr 07 '18 at 15:08
  • It should be easy to figure out the issue using the debugger. I think `rtObj` is `null`. – CodingYoshi Apr 07 '18 at 15:17

1 Answers1

0

Thoughts

Looking at your code, although there are lots of improvements and error checking that can be done, and a few places that could lead to null exceptions, the most likely (especially if it is repeating) is the fact that JsonConvert.DeserializeObject<T>() will return null if the string does not match the object type T or is badly formatted.

Without more information such as the line of error this crashed on and the RootObject code and the string returned from string finalContextRes = strReader.ReadToEnd(); it is impossible to answer in any more detail or confidence.

Proposed Answer

Without further details, it is save to assume your issue is these lines:

rtObj = JsonConvert.DeserializeObject<RootObject>(finalContextRes);
    foreach (Item i in rtObj.items)

Because rtObj is null (due to JSON string not matching the RootObject model, the rtObj.items is the position that throws the null exception.

To fix this you need to check the JSON string against your root object class and ensure they match. You can paste your JSON string here and see if your class matches up as expected.

I would also highly recommend adding error checking and exception catching where exceptions are known. So at least do if (rtObj == null) { Console.WriteLine("Failed to deserialiez root"); return; }, and then for places that could throw exceptions wrap them in try/catch blocks with specific error messages and handling

angelsix
  • 392
  • 1
  • 7