0

I have 3 c# classes in that I have 2 lists, when I trying to make a json string, I got Object reference not set to an instance of an object Error.

I have tried with one list. it perfectly works, but 2 classes or more classes have the list in my program, it not worked. pls help me resolve.

Model Json -

{
  "accessKey": "7eb228097576abf56968e9845ab51b90",
  "channelId": "103",
  "hotels": [
    {
      "hotelId": "2",
      "rooms": [
        {
          "roomId": "1"
        }
      ]
    }
  ]
}

C# Classes -

public class RootObject
{
    public string accessKey { get; set; }
    public string channelId { get; set; }
    public List<Hotel> hotels { get; set; }            
}
public class Hotel
{
    public string hotelId { get; set; }
    public List<Room> rooms { get; set; }           
}
public class Room
{
    public string roomId { get; set; }           
}

C#

public string cc() {

    string s = "";
    RootObject ro = new RootObject();
    ro.accessKey = "7eb228097576abf56968e9845ab51b90";
    ro.channelId = "103";
    ro.hotels = new List<Hotel>();

    Hotel h = new Hotel();
    Room r = new Room();

    string config = "server=localhost;username=someuser;password=somepwd;database=db";

    MySqlConnection connection = new MySqlConnection(config);

    string query = "select * from test1";

    MySqlCommand command = new MySqlCommand(query, connection);
    connection.Open();
    MySqlDataReader Reader = command.ExecuteReader();
    while (Reader.Read())
    {
         r.roomId = Reader[2].ToString();
    }
    connection.Close();

    query = "select * from test1";

    command = new MySqlCommand(query, connection);
    connection.Open();
    Reader = command.ExecuteReader();
    while (Reader.Read())
    {
        h.hotelId = Reader[1].ToString();
    }
    connection.Close();

    h.rooms.Add(r);       // Object reference not set to an instance of an object Error

    ro.hotels.Add(h);


    JavaScriptSerializer js = new JavaScriptSerializer();
    s = js.Serialize(ro);

    return s;
    }
Rune FS
  • 21,497
  • 7
  • 62
  • 96
Sagotharan
  • 2,586
  • 16
  • 73
  • 117
  • at what line do you get the error? – Rune FS Jun 23 '14 at 07:50
  • h.rooms.Add(r); I mentioned in the program sir – Sagotharan Jun 23 '14 at 07:51
  • Also, provide a [minimal, complete and verifiable example](http://stackoverflow.com/help/mcve). The sql connection is completely irrelevant to the problem. – dcastro Jun 23 '14 at 07:51
  • well yeah you did but you also provided so much unrelated information that it wasn't showing on the screen – Rune FS Jun 23 '14 at 07:52
  • Actually, you get the exception before you get to serialize your objects. So this has nothing to do with json serialization at all, and the title makes no sense. – dcastro Jun 23 '14 at 07:53
  • a comment unrelated to the question. Don't hard code connection strings, put them in a configuration file and never ever post connection strings with real users, passwords and DB names (I've removed them from your post now) if either of the fields are the same in production now is a really good time to change them – Rune FS Jun 23 '14 at 07:53
  • Duplicate of http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – dcastro Jun 23 '14 at 07:54
  • If you think that your classes are not right. What you can do is go to this http://jsonutils.com/ website and paste you're expected Json content. And this website wil translate you Json to C# classes. This can give you an indication if you are on the right path. – Fernando S. Kroes Jan 29 '16 at 08:33

4 Answers4

4

You need to initialise the Rooms property. Add a constructor to the Hotel calss that does so

public class Hotel
{
    public Hotel(string hotelId){
         this.hotelId = hotelId;
         this.rooms = New List<Room>();
    }

    public string hotelId { get; private set; }
    public List<Room> rooms { get; private set; }           
}

then you'd instantiate a room like this new Hotel(hotelId)

It's generally a good idea to keep what should not be changed encapsulated. Keys should usually not be changed from outside of the object. E.g. would it make sense to change the hotelId and keep the list of rooms?

It's recommended not to expose a setter for collections at all. Usually it's enough to expose a getter and often it's even better to expose only the required operations E.g. in this case to expose a AddRoom operation rather than exposing the list of rooms

In your code you are looping over all records in a data set (and you're doing this twice) and are overriding the value for hotelId. Ie you are only using the last record in the data set both for hotelId and for room

Rune FS
  • 21,497
  • 7
  • 62
  • 96
1

initialize rooms field. I guess it is set to null.

EDIT:

You are initializing only hotels field in the code. Good practice is to initialize fields in constructor.

klm_
  • 1,199
  • 1
  • 10
  • 26
1

Just initialize list of rooms.

public class Hotel
{
    public Hotel()
    {
        rooms = new List<Room>();
    }

    public string hotelId { get; set; }

    public List<Room> rooms { get; set; }           
}
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62
0

The r is only getting filled up with the Id or other data, when there is a while loop. It might not get executed because of the condition. That is why the r is still null.

When you pass a null value, this exception comes up. Try to give a simple id to it outside of the while loop.

Something like this:

Room r = new Room();
r.roomId = 1;

Then in the code below, alter it using while loop. If loop executed it would change the value, otherwise you'll have a non null, 1 value.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
  • it's perfectly valid to pass null to Add of a list – Rune FS Jun 23 '14 at 08:00
  • Not really you are still assuming that r is the culprit but in the line in question there's no way r can cause a nullref exception. however the field rooms is uninitialized and therefore null – Rune FS Jun 23 '14 at 08:09