-1

I'm working on the following JSON data and when trying to serialize an object I get the error

Object reference not set to an instance of an object

Here are my classes:

    public class Hotel
    {
        [JsonProperty("Hotel")]
        public Address1 Address1 { get; set; }
    }

    public class Address1
    {
        public string GuestData { get; set; }
        public string GuestName { get; set; }
        public string GuestSurName { get; set; }
    }

And I tried to serialize this way:

List<Hotel> Hotel = new List<Hotel>();
Hotel e = new Hotel();
e.Address1.GuestName = "Kevin";
e.Address1.GuestSurName = "Jones";
Hotel.Add(e);

string json = JsonConvert.SerializeObject(Hotel, Formatting.Indented);
textBox1.Text = json;

I put the code in Form_Load and I get the error

Additional information: Object reference not set to an instance of an object

What am I doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Carlos Florian
  • 171
  • 1
  • 9

1 Answers1

1

You are not assigning memory to Address1 class property inside your Hotel class. So that's why you are getting exception at line e.Address1.GuestName = "Kevin";

Try below default constructor to assign memory to Address1 class property.

public class Hotel
{
    public Hotel()
    {
        Address1 = new Address1();
    }

    [JsonProperty("Hotel")]
    public Address1 Address1 { get; set; }
}
er-sho
  • 9,581
  • 2
  • 13
  • 26
  • I tried to do it however it seems I was applying the wrong solution. Now I see what was my error. Thank you er-shoaib. Solved! – Carlos Florian Dec 08 '18 at 10:13
  • glad to hear. if my answer solved your problem then mark the tick on left side of answer to make it green :) – er-sho Dec 08 '18 at 10:13