Friday, 15 May 2015

c# - Object reference not set Error in Json Serialize in Lists -



c# - Object reference not set Error in Json Serialize in Lists -

i have 3 c# classes in have 2 lists, when trying create json string, got object reference not set instance of object error.

i have tried 1 list. works, 2 classes or more classes have list in program, 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 * 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 * 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 instance of object error ro.hotels.add(h); javascriptserializer js = new javascriptserializer(); s = js.serialize(ro); homecoming s; }

you need initialise rooms property. add together constructor hotel calss 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 room new hotel(hotelid)

it's thought maintain should not changed encapsulated. keys should not changed outside of object. e.g. create sense alter hotelid , maintain list of rooms?

it's recommended not expose setter collections @ all. it's plenty expose getter , it's improve expose required operations e.g. in case expose addroom operation rather exposing list of rooms

in code looping on records in info set (and you're doing twice) , overriding value hotelid. ie using lastly record in info set both hotelid , room

c# nullreferenceexception

No comments:

Post a Comment