c# - Json.Net JObject 的 Automapper 反射错误

标签 c# json.net automapper

将 AutoMapper 与 json.net JObject 一起使用时出现反射错误

public class Source
{
    public string Key { get; set; }
    public JObject Value { get; set; }
}

这是目标

public class Target
{
    public string Key { get; set; }
    public JObject Value { get; set; }
}

这是映射

public class SourceTargetMapping
{
    public static void IntializeMapping()
    {
        Mapper.CreateMap<Target, Source>()
            .ForMember(g => g.Value, op => op.ResolveUsing(s => s.Value));

        Mapper.CreateMap<Source, Target>()
            .ForMember(s => s.Value, op => op.ResolveUsing(g => g.Value));
    }

}

public static class SourceTargetMappingExtensions
{
    public static Source ToDomain(this Target repoItem)
    {
        var result = Mapper.Map<Target, Source>(repoItem);
        return result;
    }

    public static Target ToRepo(this Source domainItem)
    {
        var result = Mapper.Map<Source, Target>(domainItem);
        return result;
    }

    public static List<Source> ToDomain(this ICollection<Target> repoCollection)
    {
        return Mapper.Map<ICollection<Target>, List<Source>>(repoCollection);
    }

    public static List<Target> ToRepo(this ICollection<Source> domainCollection)
    {
        return Mapper.Map<ICollection<Source>, List<Target>>(domainCollection);
    }

}

这是 (NUnit) 单元测试(非空值失败,空值通过)

[TestFixture]
public class AutoMappingTest
{
  [SetUp]
  public void SetUp()
  {
    SourceTargetMapping.IntializeMapping();
    Mapper.AssertConfigurationIsValid();
  }

  [TestCase("State", "{\"State\":\"TX\"}", "Should handle normal value")]
  [TestCase("State", @"{""State"":""TX""}", "double quoted quotes")]
  [TestCase("State", "", "empty json")]
  [TestCase("State", null, "null json")]
  public void ShouldMapFromSourceToTarget(string key, string value, string description)
  {
    //arrange
    JObject jObject = (!string.IsNullOrEmpty(value)) ? JObject.Parse(value) : new JObject();
    var source = new Source() {Key = key, Value = jObject};

    //act
    var repo = source.ToRepo();

    Assert.IsNotNull(repo);
    Assert.AreEqual(key, repo.Key);
  }

这里是异常(exception):

AutoMapper.AutoMapperMappingException : 

Mapping types:
JObject -> JObject
Newtonsoft.Json.Linq.JObject -> Newtonsoft.Json.Linq.JObject

Destination path:
Target.Value

Source value:
{
  "State": "TX"
}
  ----> System.Reflection.TargetException : Object does not match target type.
at IsolationChamber.SourceTargetMappingExtensions.ToRepo(Source domainItem) in SourceTargetMapping.cs: line 62
at IsolationChamberTest.AutoMappingTest.ShouldMapFromSourceToTarget(String key, String value, String description) in AutoMapperSiteSettingTest.cs: line 35
--TargetException
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at AutoMapper.Mappers.DictionaryMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) 

感谢任何帮助。 谢谢。

最佳答案

我遇到了同样的问题,只需添加一个显式映射 JObject -> JObject 即可进行克隆。

Mapper.CreateMap<JObject, JObject>().ConvertUsing(value =>
{
    if (value == null)
        return null;

    return new JObject(value);
});

关于c# - Json.Net JObject 的 Automapper 反射错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573048/

相关文章:

c# - ASP.NET MVC 中的 Google API 图表

c# - Resharper fluent interface代码格式化(对齐圆点)

c# - Swift:将 NSDate 转换为 C# ticks

serialization - SignalR : use camel case

c# - 确定 JToken 是否为叶

c# - 将 ASP.NET Web API 2 中值类型 (C#) 的 .MinValue 序列化为 null

Automapper 8-表达式树lambda不得包含空传播运算符

c# - 如何从一直漂浮到屏幕上的小行星射出一个三角形?

c# - 使用 AutoMapper 将数据从 SuperClass 复制到 SubClass

c# - Automapper 不适用于列表?