What is the method for mapping sub-objects in Mapster?
Mapster is a library used for object mapping that helps developers map properties between two objects. Its method for mapping sub-objects is as follows:
- Configure the mapping relationship of objects using the static method TypeAdapterConfig
.ForType() from Mapster. - Define the mapping relationship for sub-objects using the TypeAdapterConfig
.Map() method. This method takes a delegate to specify the mapping logic for sub-objects.
Here is an example:
TypeAdapterConfig<Source, Destination>.ForType()
.Map(dest => dest.Child, src => src.Child); // 指定Child属性的映射规则,将Source对象的Child属性映射到Destination对象的Child属性
Destination destination = source.Adapt<Destination>(); // 使用Adapt()方法进行对象映射
In the example above, the TypeAdapterConfig
Then, the Adapt() method can be used to convert the Source object into the Destination object, where Mapster will automatically map the child objects based on the configured mapping rules.
It is important to note that when mapping child objects, make sure that the type of the child object also has a corresponding mapping relationship in the mapping configuration.