gpt4 book ai didi

c# - Automapper 序列化/反序列化源字符串以使用解析器列出

转载 作者:行者123 更新时间:2023-12-05 06:38:53 29 4
gpt4 key购买 nike

我正在尝试将源字符串映射到 List<T>对于成员,但映射成员列表属性的值始终为空。

这是我的代码。

//Source model
public class Claims
{
public int Id { get; set; }
public string ClaimType {get; set; }
public string ClaimValue { get; set; } // produce json string [{"Action":"read","Status":"active"}]
}

// Dest model
public class ClaimsDto
{
public int Id { get; set; }
public string ClaimType { get; set; }
public List<ResourceActions> ClaimValues { get; set; }
}


public class ResourceActions
{
public string Action { get; set; }
public string Status { get; set; }
}



CreateMap<ResourceActions, ResourceActions>();

CreateMap<Claims, ClaimsDto>()
.ForMember(dest => dest.ClaimValues,
opt => opt.MapFrom( src=> JsonConvert.DeserializeObject<List<ResourceActions>>(src.ClaimValue)))
.ReverseMap();

也尝试过这样的解析器。

 .ForMember(dto => dto.ClaimValues, opt => opt.ResolveUsing<CustomResolver,string>(src=>src.ClaimValue ))

解析器:

public class CustomResolver : IMemberValueResolver<Claims, ClaimsDto, string, List<ResourceActions>>
{
public List<ResourceActions> Resolve(Claims source, ClaimsDto destination, string sourceMember, List<ResourceActions> destinationMember, ResolutionContext context)
{
var data = JsonConvert.DeserializeObject<List<ResourceActions>>(sourceMember);
return context.Mapper.Map<List<ResourceActions>>(data); // not working
return JsonConvert.DeserializeObject<List<ResourceActions>>(sourceMember); // not working
}
}

和 Controller

var mapped = _mapper.Map<List<ClaimsDto>>(source); // success without exception but the list property is null.

除此 string 外,其他属性均已映射至 List<T>属性(property)。

最佳答案

我认为这个配置文件应该可以解决问题:

public class MyMapperProfile : Profile
{
public MyMapperProfile()
{
CreateMap<Claims, ClaimsDto>()
.ForMember(dto => dto.ClaimValues, cfg => cfg.MapFrom((claim, _) =>
JsonSerializer.Deserialize<IReadOnlyCollection<ResourceActions>>(claim.ClaimValue)));
}
}

这里是 an example :

var config = new MapperConfiguration(cfg => cfg.AddProfile<MyMapperProfile>());
var mapper = config.CreateMapper();

var someClaims = new List<Claims>
{
new Claims { Id = 5, ClaimType = "Foo", ClaimValue = @"[{""Action"":""read"",""Status"":""active""}]" },
new Claims { Id = 7, ClaimType = "Bar", ClaimValue = @"[{""Action"":""create"",""Status"":""disabled""}]" },
};

var result = mapper.Map<List<ClaimsDto>>(someClaims);

foreach (var item in result)
{
Console.WriteLine(JsonSerializer.Serialize(item));
}

关于c# - Automapper 序列化/反序列化源字符串以使用解析器列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45385458/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com