-1

I have this 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")));
    }

Here is an example JSON:

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

And I would like to map it automatically using the automapper.

It's working properly. But is there a way to simplify this because all those JSON Keys are just the same name as the field in the Model.

2
  • Just deserialize from JToken. Commented May 12, 2023 at 4:58
  • could you provide more context? I'm very new to c# let alone asp.net. Commented May 12, 2023 at 5:06

1 Answer 1

1

For the name of properties are the same ,you could try with

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

Or directly without AutoMapper:

ModelObject targetobject=jtoken.ToObject<ModelObject>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.