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;
}