asp.net 与模型字段同名的JSON键的AutoMapper

jrcvhitl  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(135)

我有这个AutoMapperProfile:

public AutoMapperJSON()
    {
        CreateMap<JToken, ModelObject>()
           .ForMember(dest => dest.name, opt => opt.MapFrom(src => src.SelectToken("name")))
           .ForMember(dest => dest.unformatted_street, opt => opt.MapFrom(src => src.SelectToken("unformatted_street")))
           .ForMember(dest => dest.city, opt => opt.MapFrom(src => src.SelectToken("city")))
           .ForMember(dest => dest.state, opt => opt.MapFrom(src => src.SelectToken("state")))
           .ForMember(dest => dest.postcode, opt => opt.MapFrom(src => src.SelectToken("postcode")))
           .ForMember(dest => dest.street, opt => opt.MapFrom(src => src.SelectToken("street")))
           .ForMember(dest => dest.locality, opt => opt.MapFrom(src => src.SelectToken("locality")))
           .ForMember(dest => dest.id, opt => opt.MapFrom(src => src.SelectToken("id")))
           .ForMember(dest => dest.short_id, opt => opt.MapFrom(src => src.SelectToken("short_id")))
           .ForMember(dest => dest.formatted_street, opt => opt.MapFrom(src => src.SelectToken("formatted_street")))
           .ForMember(dest => dest.created_at, opt => opt.MapFrom(src => src.SelectToken("created_at")))
           .ForMember(dest => dest.updated_at, opt => opt.MapFrom(src => src.SelectToken("updated_at")))
           .ForMember(dest => dest.updated_by, opt => opt.MapFrom(src => src.SelectToken("updated_by")))
           .ForMember(dest => dest.deleted_at, opt => opt.MapFrom(src => src.SelectToken("deleted_at")));
    }

下面是一个JSON示例:

{ "id":"sample1",
"name":"sample2",
"city":"sample3",
"state":"sample4",
...
"created_at":"sample5",
"updated_at":"sample6",
"updated_by":"sample7",
"deleted_at":"sample8"}

我想用自动Map器自动Map它。
它工作正常但是,有没有一种方法可以简化这一点,因为所有这些JSON键都与模型中的字段名称相同。

mwngjboj

mwngjboj1#

如果属性的名称相同,可以尝试使用

CreateMap<JToken, ModelObject>().ConvertUsing(x => x.ToObject<ModelObject>() ?? default!);

或者直接不使用AutoMapper:

ModelObject targetobject=jtoken.ToObject<ModelObject>()

相关问题