3

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.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Night Monger
  • 770
  • 1
  • 10
  • 33
  • Create a constructor of Employee and pass an object of ThirdPartyEmployee like this `public Employee(ThirdPartyEmployee tpeObj){/* Assign in this constructor */}` – GSP Jan 24 '17 at 03:45
  • you can take a look automapper, [automapper starter guide](https://github.com/AutoMapper/AutoMapper/wiki/Getting-started) – Sreepathy Sp Jan 24 '17 at 04:15
  • I think you should add the tag json.net. Here casting is done by json converter. so i think it should belongs to tag – Eldho Jan 24 '17 at 07:48

2 Answers2

4

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

Community
  • 1
  • 1
MrVoid
  • 709
  • 5
  • 19
2

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

Community
  • 1
  • 1
Eldho
  • 7,795
  • 5
  • 40
  • 77
  • thanks @Eldho.. Quick question. Can i do this for multilevel? like for eg: if i want to map [JsonProperty("Id.Val")] to EmpId? – Night Monger Jan 24 '17 at 16:02
  • I think rather than doing a multi level , place the object in ur model and try to map within the property. – Eldho Jan 24 '17 at 16:15