Skip to content
Advertisement

ModelMapper returning source object type when mapping derived class to a base class

Let’s suppose I have classes:

JavaScript

I have an instance of B called b and want to map to A (to get rid of z property as it’s getting serialized later). I was trying to do;

JavaScript

But as a result I am getting the the same type B object. I suspect it could be because B is a subclass of A, so there is no point in converting types, because B satisfies A, but it’s just my suspicion.

Can I somehow tell ModelMapper do convert the type to the exact one I want? Maybe there is a better way of doing that?

Advertisement

Answer

You can do this with a custom TypeMap

Conside the following example code:

JavaScript

With output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement