Night Monger
Night Monger

Reputation: 780

Map two different objects with different properties

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.

Upvotes: 3

Views: 10195

Answers (2)

Eldho
Eldho

Reputation: 8273

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

Upvotes: 2

MrVoid
MrVoid

Reputation: 709

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

Upvotes: 4

Related Questions