Tworzenie i serializacja obiektu

0

Próbuje zserializować json'a. W tym celu stworzyłem klasę Car

  class Car
    {
        public Id id { get; set; }
            }
    public class Id
    {
        public string brand { get; set; }
        public string model { get; set; }
        public string year { get; set; }
        public string r_no { get; set; }
        public string owner { get; set; }
    }

Później, chce wykonać wspomnianą operację po kliknięciu guzika


  private void saveButton_Click(object sender, EventArgs e)
        {

          Car Auto1 = new Car();
          Id id = new Id();
          Auto1.id.brand = textBox1.Text;
          Auto1.id.model = textBox2.Text;
          Auto1.id.year = textBox3.Text;
          Auto1.id.r_no = textBox4.Text;
          Auto1.id.owner = textBox5.Text;

            string json = JsonConvert.SerializeObject(Auto1);
            MessageBox.Show(json);
        }

Cały czas dostaje nullpointer exception ale nie wiem za bardzo dlaczego. Obiekt jest stworzony poprawnie wg mnie? Inicjuje go przy przypisaniu do Textboxa?

3

Tworzysz sobie niezależny obiekt klasy Id (o nazwie id), ale obiekt Id, który jest właściwością twojego obiektu klasy Car jest nullem.

Car auto1 = new Car();
auto1.Id = new Id();
auto1.Id.Brand = "Polonez";

W zasadzie aby automatycznie tworzyć obiekt klasy Id, możesz sobie w swojej klasie Car zrobić konstruktor:

class Car
{
    public Id Id { get; set; }

    public Car()
    {
        this.Id = new Id();
    }
}

Swoją drogą nazwa klasy "id" jest słaba, bo nic nie mówi - Id to dla mnie identyfikator, coś prostego, a u ciebie to zbiór informacji o samochodzie. Dlaczego nie wrzucić ich bezpośrednio do klasy Car?

1 użytkowników online, w tym zalogowanych: 0, gości: 1