简体   繁体   中英

Automapper:Converting object to JSON

In my scenario, i would like to map a json to a concrete type, and the other way around using automapper version 6 with .net core.

Based on this answer - https://stackoverflow.com/a/38108128/6602770 I managed to map the JSON to the desired type. However, i do not seem to be able to reverse map it back to its JSON format.

My code looks like this:

The mapping profile:

 CreateMap<JToken, SomeDto>()
            .ForMember(dest => dest.ObjectId, cfg => { cfg.MapFrom(jo => jo["objectId"]); })
            .ReverseMap()
            .ForAllOtherMembers(x => x.Ignore());

and the mapping:

var json = _mapper.Map<JToken>(someDto);

There is no error, but it returned null. I have also tried to set the profile with JObject instead of JToken, same result.

I also tried to create a seperate mapping profile, instead of using the "ReverseMap"

 public class SomeDtoProfile : Profile
{
    public SomeDtoProfile()
    {
        CreateMap<SomeDto, JObject>()
            .ForMember(dest=> dest["objectId"], cfg => { cfg.MapFrom(src => src.ObjectId); })
            .ForAllOtherMembers(x => x.Ignore());

    }
}

but this throws an error of: "Custom configuration for members is only supported for top-level individual members on a type json"

I would really like the solution the be using the AutoMapper, is it all possible or am i missing something basic ?

Use the JObject.FromObject static factory method within your Mapper profile.

public class SomeDtoProfile : Profile
{
    public SomeDtoProfile()
    {
        CreateMap<SomeDto, JObject>()
            .ConvertUsing(JObject.FromObject);
    }
}

public class SomeDto    
{
    public string Name { get; set; }
}

then if we run the following test

public class Tests
{
    [Fact]
    public void ShouldReturnJson()
    {
        Mapper.Initialize(cfg => cfg.AddProfile(new SomeDtoProfile()));


        var jObject = Mapper.Map<JObject>(new SomeDto {Name = "Bob"});

        Assert.Equal("{\r\n  \"Name\": \"Bob\"\r\n}", jObject.ToString());
    }
}

All is Green!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM