2

I retrieve employee data from SAP in a json format. I am able to deserialize this into a C# object. I then need to put some of this data into another object and post it to a webservice, but the field names and structure is different.

How do I efficiently translate one "employee object" to a different object?

Instead of doing this (entirely fictional code)

sapEmployee = await SAPService.GetSomeEmployee();

Employee employee = new Employee();
employee.Name = sapEmployee.FullName;
employee.Emailaddress = sapEmployee.Email;
employee.Phone = sapEmployee.Phone.Mobile;
//etc
SomeClass.PostToTheOtherWebService(employee);

What is the principle of doing something like this and what is good architecture? Some sort of intermediate classes or field mapping configuration?

Tony Arntsen
  • 123
  • 1
  • 8
  • You could use [user defined conversions](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators) or use anoymous types(although I would recommend user defined conversions. – DekuDesu May 25 '21 at 06:51
  • If you're posting it in json instead of an object, consider [manipulating the json directly](https://stackoverflow.com/a/21695462/15204525) if you want to avoid creating, casting, or needlessly converting objects back into json – DekuDesu May 25 '21 at 06:54
  • 1
    Honestly, I don't see anything wrong with this code. You _could_ use something like AutoMapper, but if the PorpertyNames do not match, you'd have to configure it, so it does exactly what you did manually here. So the benefit of using AutoMapper would be debatable. – Fildor May 25 '21 at 07:16
  • That's fine. What you can do is use an Automapper. Pro: You can automatically check if every property is filled. Con: does not simplify anything and instead of code everybody can read you have to use special Automapper "syntax". – Klamsi May 25 '21 at 07:30
  • There are Xml transform (xslt), and there seem to be some [tools that can be used for json](https://stackoverflow.com/questions/1618038/xslt-equivalent-for-json). But if there are a few objects, just doing it by hand, as in the example, is probably simpler and easier. – JonasH May 25 '21 at 08:20

0 Answers0