Saturday, March 24, 2012

List<>.Add adds reference of object instead of object itself

Hey everyone,

I'm trying to parse a JSON response into a List<object> and I've run into a problem. The general program flow is as follows:

List oBusiness =new List<>;Business TempBusiness =new Businessforeach (Business t_businessin (JsonArray)businesses){//load business data into TempBusiness oBusiness.Add(TempBusiness);}return oBusiness;

However, my returned list only contains the last item parsed for every object in the List. Does anyone have a suggestion?

Thanks in advance!

Based on your code above, your logic is wrong.

List oBusiness =new List<>;

Business TempBusiness =new Business

foreach (Business t_businessin (JsonArray)businesses)
{
//load business data into TempBusiness
oBusiness.Add(t_business);

}

return oBusiness;

 
The underlined intalics isn't needed. Where I have it in bold is what you need to do. 

Oops, my bad. The t_business is actually of type JsonObject. I have to manually type cast each element into a business object and return a List of (Business) objects. Sorry about the confusion.

List oBusiness =new List<>;

Business TempBusiness =new Business

foreach (JsonObject t_businessin (JsonArray)businesses)
{
//load business data into TempBusiness

 TempBusiness.Address1 = business["address1"].ToString();
TempBusiness.Address2 = business["address2"].ToString();
 //etc. 

oBusiness.Add(TempBusiness);

}

return oBusiness;


List oBusiness =new List<>;

foreach (JsonObject t_businessin (JsonArray)businesses)
{
//load business data into TempBusiness
Business TempBusiness =new Business

 TempBusiness.Address1 = business["address1"].ToString();
TempBusiness.Address2 = business["address2"].ToString();
 //etc. 

oBusiness.Add(TempBusiness);

}

return oBusiness;

Remember C# is Managed Code. Meaning when you create an object, that object is always taht object. You should re initialize your Business object. That should do the trick.


Oh yeah! Thanks alot.

I still get C# mixed up with C++ sometimes. :-P

0 comments:

Post a Comment