I have a complex json object which I am deserializing to dto class in API. While mapping this class to model class, I have tried two options:
- IConverter interface and implementation for each class.
- Static Mapper Classer
For eg: Json Object:
{
"Response":
{
"Detail": {
"Subject": "GE",
"Address": {
"CountryCode": "US"
}
}
}
}
For this Object, Response class would have property of type Detail class, which would have properties of type Subject ,Address etc.
Hence for 1st approach, I had to create separate class mapper for each class in source and destination. like:
public class DetailMapper<DetailDto, DetailModel>:IConvert<DetailDto,
DetailModel>
{
private IConvert<SubjectDto,SubjectModel> subconvert;
private IConvert<AddressDto,AddressModel> addconvert;
public DetailMapper(IConvert<SubjectDto,SubjectModel>
sub,IConvert<AddressDto,AddressModel> add)
{
subconvert=sub;
addconvert=add;
}
public DetailModel Convert(DetailDto detailDto)
{
//logic
}
}
When JSON Object is more complex, this pattern is less readable with more converter implementations for each class injected.
2.For 2nd approach, I created single mapper class with static methods to convert dto classes to model like:
public class Mapper()
{
public static ResponseModel Convert(ResponseDto res)
{
//logic
}
public static DetailModel Convert(DetailDto det)
{
//logic
}
}
2nd approach seems to be providing me more readability, but I am concerned if it is ok to use static methods for mapper class in Api.
I would like to know what are the best approaches and pattern for mapping 2 classes in c#.
Aucun commentaire:
Enregistrer un commentaire