简体   繁体   中英

Map two different objects with different properties

I have a Class with set of properties for eg:

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.

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

If you are using NewtonSoft you can try using JsonPropertyAttribute

class ThirdPartyEmployee
{
  [JsonProperty("Id")]
  string EmpId {get ; set ; }

}

This will map json property of Id to EmpId

Similar question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM