Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map two different objects with different properties

Tags:

c#

.net

casting

I have a Class with set of properties for e.g.:

class Employee 
{
    string Id {get ; set ; }
    string Name {get ; set ; }
    string Lastname {get ; set ; }
    string email {get ; set ; }
}

I have another object - I get the data from some third party as API string. I used NewtonSoft Json to deserialize them. Their structure looks something like this:

class ThirdPartyEmployee
{
    string EmpId {get ; set ; }
    string fName {get ; set ; }
    string LName {get ; set ; }
    string emailID {get ; set ; }
    string Phonenumber {get ; set ; }
}

For reasons of simplicity - I cannot change the property of both the classes.

Now the question is, when I receive the json object,

List<Employee> obj1 = new List<Employee>();
List<ThirdPartyEmployee> obj2 = JsonConvert.DeserializeObject<List<ThirdPartyEmployee>>(JsonConvert.SerializeObject(responseString));

Now I need to cast obj2 as obj1. While I can do it manually by saying:

foreach (var currObj2 in obj2) 
{
    Employee  employee = null ; 

    employee .Id = currObj2 .EmpId; 
    employee.Name = currObj2.fName;
    employee.Lastname = currObj2.LName;
    employee.email = currObj2.emailID;
    obj1.add(employee); 
}

Is there an easier way to do this with some mapping mechanism?

While I have given an easier example, the actual scenario is much more complex with sub objects and lot more properties.

like image 823
Night Monger Avatar asked Mar 16 '26 07:03

Night Monger


1 Answers

Take a look to AutoMapper my friend, is what you are looking for http://automapper.org/

Here you have a old question that may help you

How to handle custom Properties in AutoMapper

like image 135
MrVoid Avatar answered Mar 17 '26 20:03

MrVoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!